-2

我即将实施一个小程序,我需要从 1970 年 1 月 1 日 00:00:00 UTC 到 2009 年 6 月 22 日 00:00:00 UTC 所经过的秒数。谁能指出我正确的方向,至于如何实现这一点。

4

2 回答 2

2
public static void main(String[] args) {
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    calendar.set(2009, 5, 22, 0, 0, 0);
    System.out.println("ms: " + calendar.getTimeInMillis());
}

If you want to parse String representation of Date, take a look at SimpleDateFormat. Although it was suggested in one answer, you should avoid using static instances as they are not thread safe.

于 2012-06-19T22:49:39.587 回答
0

Sure: It's easy to get milliseconds since the epoch:

long ms = System.currentTimeMillis();

Here's how you get milliseconds from a specific time:

private static final String DEFAULT_PATTERN = "yyyy-MMM-dd hh:mm:ss";
private static final DateFormat FORMATTER;

static {
    FORMATTER = new SimpleDateFormat(DEFAULT_PATTERN);
    FORMATTER.setLenient(false);
}

public static long getDateMilliseconds(String dateStr) throws ParseException {
    return FORMATTER.parse(dateStr).getTime();
}
于 2012-06-19T22:41:00.060 回答