简体   繁体   English

java中如何将时间戳转换为日期格式

[英]How to convert Timestamp into Date format in java

I have a time stamp like this(form a json response) :我有一个像这样的时间戳(形成一个 json 响应):

"/Date(1479974400000-0800)/" "/日期(1479974400000-0800)/"

I'm trying this function to convert time stamp into date:我正在尝试使用此功能将时间戳转换为日期:

public String getDate() {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time);
    String date = DateFormat.format("dd-MM-yyyy", cal).toString();
    return date;
}

How to convert this Timestamp into Date format?如何将此时间戳转换为日期格式?

Parse directly into an OffsetDateTime直接解析成 OffsetDateTime

Java can directly parse your string into an OffsetDateTime . Java 可以直接将您的字符串解析为OffsetDateTime Use this formatter:使用此格式化程序:

private static final DateTimeFormatter JSON_TIMESTAMP_FORMATTER 
        = new DateTimeFormatterBuilder()
                .appendLiteral("/Date(")
                .appendValue(ChronoField.INSTANT_SECONDS, 1, 19, SignStyle.NEVER)
                .appendValue(ChronoField.MILLI_OF_SECOND, 3)
                .appendOffset("+HHMM", "Z")
                .appendLiteral(")/")
                .toFormatter();

Then just do:然后做:

    String time = "/Date(1479974400000-0800)/";
    OffsetDateTime odt = OffsetDateTime.parse(time, JSON_TIMESTAMP_FORMATTER);
    System.out.println(odt);

Output is:输出是:

2016-11-24T00:00-08:00 2016-11-24T00:00-08:00

In your string 1479974400000 is a count of milliseconds since the epoch of Jan 1, 1970 at 00:00 UTC, and -0800 is an offset of -8 hours 0 minutes from UTC (corresponding for example to Pacific Standard Time).在您的字符串中, 1479974400000是自 1970 年 1 月 1 日 00:00 UTC 的纪元以来的毫秒数,而-0800是距 UTC 的 -8 小时 0 分钟的偏移量(例如对应于太平洋标准时间)。 To parse the milliseconds we need to parse the seconds since the epoch (all digits except the last three) and then the millisecond of second (the last three digits).要解析毫秒,我们需要解析自纪元以来的秒数(除最后三位之外的所有数字),然后解析秒的毫秒(最后三位)。 By specifying the width of the milliseconds field as 3 Java does this.通过将毫秒字段的宽度指定为 3 Java 可以做到这一点。 For it to work it requires that the number is at least 4 digits and not negative, that is not within the first 999 milliseconds after the epoch or earlier.为了使其工作,它要求该数字至少为 4 位而不是负数,即不在纪元之后的前 999 毫秒内或更早。 This is also why I specify in the formatter that the seconds must not be signed.这也是我在格式化程序中指定不得对秒进行签名的原因。

I specified Z for offset zero, I don't know if you may ever receive this.我将Z指定为偏移量为零,我不知道你是否会收到这个。 An offset of +0000 for zero can still be parsed too.仍然可以解析零的+0000偏移量。

Original answer: parse the milliseconds and the offset separately and combine原始答案:分别解析毫秒和偏移量并结合

First I want to make sure the timestamp I have really lives up to the format I expect.首先,我想确保我拥有的时间戳确实符合我期望的格式。 I want to make sure if one day it doesn't, I don't just pretend and the user will get incorrect results without knowing they are incorrect.我想确保有一天它没有,我不只是假装用户会得到不正确的结果而不知道它们是不正确的。 So for parsing the timestamp string, since I didn't find a date-time format that would accept milliseconds since the epoch, I used a regular expression:因此,为了解析时间戳字符串,由于我没有找到可以接受自纪元以来毫秒数的日期时间格式,所以我使用了正则表达式:

    String time = "/Date(1479974400000-0800)/";
    Pattern pat = Pattern.compile("/Date\\((\\d+)([+-]\\d{4})\\)/");
    Matcher m = pat.matcher(time);
    if (m.matches()) {
        Instant i = Instant.ofEpochMilli(Long.parseLong(m.group(1)));
        System.out.println(i);
    }

This prints:这打印:

2016-11-24T08:00:00Z

If you want an old-fashioned java.util.Date :如果你想要一个老式的java.util.Date

        System.out.println(Date.from(i));

On my computer it prints在我的电脑上打印

Thu Nov 24 09:00:00 CET 2016

This will depend on your time zone.这将取决于您的时区。

It is not clear to me whether you need to use the zone offset and for what purpose.我不清楚您是否需要使用区域偏移量以及用于什么目的。 You may retrieve it from the matcher like this:您可以像这样从匹配器中检索它:

        ZoneOffset zo = ZoneOffset.of(m.group(2));
        System.out.println(zo);

This prints:这打印:

-08:00

The zone offset can be used with other time classes, like for instance OffsetDateTime .区域偏移量可以与其他时间类一起使用,例如OffsetDateTime For example:例如:

        OffsetDateTime odt = OffsetDateTime.ofInstant(i, zo);
        System.out.println(odt);

I hesitate to mention this, though, because I cannot know whether it is what you need.不过,我不愿提及这一点,因为我不知道它是否是您需要的。 In any case, it prints:在任何情况下,它都会打印:

2016-11-24T00:00-08:00

如果按日期表示 Date 实例,那么您可以这样做:

new Date(Long.parseLong("\/Date(1479974400000-0800)\/".substring(7, 20)));

I assume this info in holding the String representing an Epoch and a TimeZone我假设此信息保存代表 Epoch 和 TimeZone 的字符串

"/Date(1479974400000-0800)/" "/日期(1479974400000-0800)/"

you need to get rid off the all the not necessary parts and keeping only the 1479974400000-0800你需要去掉所有不必要的部分,只保留1479974400000-0800

then the epoch is 1479974400000 and I guess the Timezone is 0800那么时代是1479974400000我猜时区是0800

then do:然后做:

String[] allTimeInfo = "1310928623-0800".split("-");
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
Date time = new java.util.Date(Long.parseLong(allTimeInfo[0]));
System.out.println(time);
System.out.println(timeZoneFormat.format(time));

The solution works for me is like this:对我有用的解决方案是这样的:

 String str = obj.getString("eventdate").replaceAll("\\D+", "");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));

Date time = new java.util.Date(Long.parseLong(upToNCharacters));
//                                System.out.println(time);
model.setDate(String.valueOf(timeZoneFormat.format(time)));

Use time variable where you want在需要的地方使用时间变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM