如何在没有SimpleDateFormat的情况下获得UTC时间?

时间:2014-06-13 08:31:28

标签: java datetime utc

我正在处理从UTC转换为UTC的时间戳。我找到的所有文章都基于与String的转换。 Like this one:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(rawQuestion.getString("AskDateTime"));

但我想知道是否有办法简单地使用Date实例/类或日历将本地Date转换为UTC,反之亦然,而不将其转换为String。

4 个答案:

答案 0 :(得分:2)

阅读Joda-Time。这是比java日期和日历类

更好的API

答案 1 :(得分:0)

也许这可以帮到你:

Calendar.getInstance(java.util.TimeZone)

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

答案 2 :(得分:0)

java.until.Date没有时区,所以没有任何东西可以转换。只有在显式地将日期格式化为字符串时才会看到时区,或者使用其toString方法隐式地显示时区。隐式转换使用本地默认时区。

在内部,日期将日期/时间存储为长,表示自UTC,1970年1月1日午夜起的毫秒数。

因此,如果您将日期格式化为字符串,然后将字符串解析回日期,那么您根本没有改变任何内容。

答案 3 :(得分:0)

到目前为止,我找不到完美的解决方案,所以我不得不坚持从Date到String的转换,反之亦然。这是我写的一个小助手类。

public class DateTimeHelper {

    public static final String MYSQL_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final TimeZone timeZoneUTC = TimeZone.getTimeZone("UTC");

    private Date date = new Date();
    private final SimpleDateFormat format;

    public DateTimeHelper(String dateTimeFormat) {
        format = new SimpleDateFormat(dateTimeFormat, Locale.US);
    }

    public DateTimeHelper(String dateTimeFormat, String utcTimeString) {
        this(dateTimeFormat);

        try {
            format.setTimeZone(timeZoneUTC);
            Date utc = format.parse(utcTimeString);
            format.setTimeZone(TimeZone.getDefault());
            String local = format.format(utc);
            date = format.parse(local);
        } catch (ParseException e) {
            // nothing
        }
    }

    public Date getDate() {
        return date;
    }

    public Date toUtc() {

        String temp = toString();
        format.setTimeZone(timeZoneUTC);
        try {
            return format.parse(temp);
        } catch (ParseException e) {
            return date;
        }
    }

    @Override
    public String toString() {
        format.setTimeZone(TimeZone.getDefault());
        return format.format(date);
    }

    public String toUtcString() {
        format.setTimeZone(timeZoneUTC);
        return format.format(date);
    }
}

另一个更容易使用的方法:

public class MySqlDateTimeHelper extends DateTimeHelper {

    public MySqlDateTimeHelper() {
        super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT);
    }

    public MySqlDateTimeHelper(String utcTimeString) {
        super(DateTimeHelper.MYSQL_DATE_TIME_FORMAT, utcTimeString);
    }

    public static String getCurrentTimestampUtc() {
        MySqlDateTimeHelper current = new MySqlDateTimeHelper();
        return current.toUtcString();
    }
}