java字符串到utc日期 [英] java string to utc date

查看:137
本文介绍了java字符串到utc日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题是此问题重复意图。似乎较旧的一个被忽略,而答案中没有一个答案。

This question is a duplicate of this question by intention. It seems like the older one is "ignored", while none of the answers there is the answer.

我需要用给定的日期模式/格式解析给定日期。

I need to parse a given date with a given date pattern/format.

我有这个代码,应该工作:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main
{

    public static void main(String[] args)
    {
        final Date date = string_to_date("EEE MMM dd HH:mm:ss zzz yyyy",
                "Thu Aug 14 16:45:37 UTC 2011");
        System.out.println(date);
    }

    private static Date string_to_date(final String date_format,
            final String textual_date)
    {
        Date ret = null;

        final SimpleDateFormat date_formatter = new SimpleDateFormat(
                date_format);
        try
        {
            ret = date_formatter.parse(textual_date);
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }

        return ret;
    }
}

出于某种原因,我得到了这个输出:

For some reason I'm getting this output:

java.text.ParseException: Unparseable date: "Thu Aug 14 16:45:37 UTC 2011"
    at java.text.DateFormat.parse(DateFormat.java:337)
    at Main.string_to_date(Main.java:24)
    at Main.main(Main.java:10)
null

我的日期模式有什么问题?这似乎是一个谜。

What's wrong with my date pattern? This seems to be a mystery.

推荐答案

您的平台默认语言环境显然不是英语。 周四八月是英文。您需要明确指定 区域设置 SimpleDateFormat 构造函数中的第二个参数:

Your platform default locale is apparently not English. Thu and Aug are English. You need to explicitly specify the Locale as 2nd argument in the constructor of SimpleDateFormat:

final SimpleDateFormat date_formatter = 
    new SimpleDateFormat(date_format, Locale.ENGLISH); // <--- Look, with locale.

如果没有它,将使用平台默认语言环境来解析日/月名称。您可以通过 区域设置#getDefault() 以下方式:

Without it, the platform default locale will be used instead to parse day/month names. You can learn about your platform default locale by Locale#getDefault() the following way:

System.out.println(Locale.getDefault());

这篇关于java字符串到utc日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆