【问题标题】:Round UTC date to nearest 5 minutes [duplicate]将 UTC 日期四舍五入到最接近的 5 分钟 [重复]
【发布时间】:2014-04-02 04:38:58
【问题描述】:

我有以下代码来获取日期时间 UTC。

public static Date GetUTCdatetimeAsDate()
{
    return StringDateToDate(GetUTCdatetimeAsString());
}

public static String GetUTCdatetimeAsString()
{
    final SimpleDateFormat sdf = new SimpleDateFormat(DATEFORMAT);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    final String utcTime = sdf.format(new Date());

    return utcTime;
}

public static Date StringDateToDate(String StrDate)
{
    Date dateToReturn = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);

    try
    {
        dateToReturn = (Date)dateFormat.parse(StrDate);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }

    return dateToReturn;
}

现在我想使用 GETUTCdatetimeAsDate ,如果我得到例如 11/22/2014 03:12 分钟将四舍五入到最接近的 5 分钟。所以在这种情况下,这将是 2014 年 11 月 22 日 03:15。如果是 11/22/2014 03:31,它将是 11/22/2014 03:35。

关于如何实现这一目标的任何想法?

【问题讨论】:

  • 所以你只想要最小的。围捕?我的意思是如果是 15:01 你想要 15:05

标签: java android date


【解决方案1】:
public static Date StringDateToDate(String StrDate) {
    Date dateToReturn = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);
    try {
        dateToReturn = (Date) dateFormat.parse(StrDate);
    } catch (ParseException e) {
        e.printStackTrace();
        return null;
    }

    Calendar c = Calendar.getInstance();
    c.setTime(dateToReturn);
    int minute = c.get(Calendar.MINUTE);
    minute = minute % 5;
    if (minute != 0) {
        int minuteToAdd = 5 - minute;
        c.add(Calendar.MINUTE, minuteToAdd);
    }

    return c.getTime();
}

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    相关资源
    最近更新 更多