java - 日期和时区问题如何获取没有时区的日期?

标签 java

我尝试将 Tics 中的日期转换为 UTC 日期时间格式 - 'YYYY-MM-DDThh:mm:ss'

public static DateFormat getFormat() {
    String systemLocale = System.getProperty("user.language"); //$NON-NLS-1$ 
    Locale locale = new Locale(systemLocale);
    DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
    return dateFormat;
}

public static Object getFormatedValue(Object value) {
        String updated = (strValue).replaceAll(pattern, "$1"); //$NON-NLS-1$
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(Long.parseLong(updated));
        return getFormat().format(new Date(calendar.getTimeInMillis()));
}

public static Object getOdataValue(Object value) throws ParseException {

    DateFormat dateFormat = getFormat();

    Date parse = dateFormat.parse(value.toString());
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(parse.getTime());

    return "\"/Date(" + calendar.getTimeInMillis() + ")/\""; //$NON-NLS-1$ //$NON-NLS-2$

}

以 UTC 为例,我得到 dtae 时间结果的问题 -

1393358368000 = 2014 年 2 月 25 日星期二 19:59:28 GMT

您的时区:2014 年 2 月 25 日晚上 9:59:28 GMT+2

此代码的结果是 2/25/2014 21:59:28 PM

如何获得没有时区的结果?在这种情况下,我希望结果为 ue, 25 Feb 2014 19:59:28 GMT 我可以勾选并在有和没有 UTC 的情况下得到不同的结果吗?

最佳答案

尚不完全清楚您要问什么,但如果您只想让您的 DateFormat 使用 UTC,那很简单:

public static DateFormat getFormat() {
    String systemLocale = System.getProperty("user.language"); //$NON-NLS-1$ 
    Locale locale = new Locale(systemLocale);
    DateFormat dateFormat = DateFormat.getDateTimeInstance(
        DateFormat.MEDIUM, DateFormat.MEDIUM, locale);
    dateFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
    return dateFormat;
}

(顺便问一下,您不使用 Locale.getDefault() 作为默认区域设置有什么原因吗?或者让 DateFormat 自行选择它?)

另请注意,您创建日历根本没有任何原因。您的 getFormattedValuegetOdataValue 方法可以简化为:

public static Object getFormattedValue(Object value) {
    String updated = (strValue).replaceAll(pattern, "$1"); //$NON-NLS-1$
    long millis = Long.parseLong(updated);
    return getFormat().format(new Date(millis));
}

public static Object getOdataValue(Object value) throws ParseException {
    DateFormat dateFormat = getFormat();
    Date parsedDate = dateFormat.parse(value.toString());
    return "\"/Date(" + date.getTime() + ")/\""; //$NON-NLS-1$ //$NON-NLS-2$
}

关于java - 日期和时区问题如何获取没有时区的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22052320/

相关文章:

java - 如何以编程方式为另一个 xml 文件设置 Textview 的背景颜色?

java - 带有java配置的Spring Batch

java - 制作独立的 Java EXE 文件

java - rxJava : composing single with completable and return single

java - 如何从其自己的操作监听器更改 menuItem 工具提示?

java - Spring @RequestBody 与 GeoJsonPoint

Java - 获取一个从100到999的随机数

Java-JDBC-MySQL错误

java - 为什么 Jsoup 中没有执行循环?

java - 如何更改 JTable 标题背景颜色?