2009-07-11 38 views
4
  1. 如何从日期对象中提取时间部分并在J2ME中将其用作字符串?Java - 在J2ME中使用日期/时间

  2. 如何将该时间字符串转换回日期 - J2ME中的对象?

我已经做了一些事情来实现这一点,但它没有显示正确的时间。

+0

您正在使用来自核心库,日期时间或任何其他? – Macarse 2009-07-11 15:04:59

+0

我正在使用java.utils.Date – 2009-07-11 15:08:27

回答

7

我用下面的代码获取时间

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); 
} 

那会做的伎俩。

0

如果您使用的是CDC,您可以访问java.text.DateFormat,这是(据我所知)处理非Joda时间使用代码的日期/时间的“标准”方式。

如果您使用CLDC,则可能需要手动滚动某些东西,因为它没有java.text包。