gpt4 book ai didi

datetime - Java - 在 J2ME 中处理日期/时间

转载 作者:行者123 更新时间:2023-12-05 00:08:52 25 4
gpt4 key购买 nike

  • 如何从日期对象中提取时间部分并将其用作 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 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);
    }

    这样就行了。

    关于datetime - Java - 在 J2ME 中处理日期/时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1113890/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com