【发布时间】:2014-03-27 12:20:25
【问题描述】:
如何从日期对象中提取时间部分并将其用作 J2ME 中的字符串?
如何在 J2ME 中将该时间字符串转换回日期 - 对象?
我已经做了一些事情来实现这一点,但它没有显示正确的时间。
【问题讨论】:
-
您正在使用核心库中的日期、joda 时间或任何其他日期?
如何从日期对象中提取时间部分并将其用作 J2ME 中的字符串?
如何在 J2ME 中将该时间字符串转换回日期 - 对象?
我已经做了一些事情来实现这一点,但它没有显示正确的时间。
【问题讨论】:
我使用以下代码来获取时间:
String getDateString(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
return new String(/*Any format you need*/);
}
你得到数字,然后你可以以任何必要的格式输出它们。
创建 Date 对象的代码是这样的:
Date createDate(String dateString) {
//Extract needed numbers first
StringBuffer strBuf = new StringBuffer(dateString);
char[] charBuf = new char[4];
strBuf.getChars(0, 3, charBuf, 0);
dayOfWeek = new String(charBuf, 0, 3);
strBuf.getChars(strBuf.length() - 4, strBuf.length(), charBuf, 0);
year = charsToInt(charBuf, 4);
strBuf.getChars(4, 7, charBuf, 0);
String monthStr = new String(charBuf, 0, 3);
month = ArraySearcher.searchStringEntry(monthStr, MONTHS);
day = extractShortField(strBuf, 8, charBuf);
hour = extractShortField(strBuf, 11, charBuf);
minute = extractShortField(strBuf, 14, charBuf);
second = extractShortField(strBuf, 17, charBuf);
//Now set the calendar
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
return calendar.getTime();
}
private int charsToInt(char[] buf, int len) {
String str = new String(buf, 0, len);
return Integer.parseInt(str);
}
private int extractShortField(StringBuffer strBuf, int start, char[] charBuf) {
strBuf.getChars(start, start + 2, charBuf, 0);
return charsToInt(charBuf, 2);
}
这样就可以了。
【讨论】:
如果您使用 CDC,您可以访问 java.text.DateFormat,这是(据我所知)处理非 Joda-Time 使用代码的日期/时间的“标准”方式。
如果您使用 CLDC,您可能需要手动滚动一些东西,因为它没有 java.text 包。
【讨论】: