简体   繁体   English

转换纪元中的日期格式

[英]Convert a date format in epoch

I have a string with a date format such as我有一个日期格式的字符串,例如

Jun 13 2003 23:11:52.454 UTC

containing millisec... which I want to convert in epoch.包含毫秒...我想在纪元中转换。 Is there an utility in Java I can use to do this conversion? Java 中是否有实用程序可以用来进行此转换?

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:此代码显示如何使用java.text.SimpleDateFormat从字符串解析java.util.Date

String str = "Jun 13 2003 23:11:52.454 UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz");
Date date = df.parse(str);
long epoch = date.getTime();
System.out.println(epoch); // 1055545912454

Date.getTime() returns the epoch time in milliseconds. Date.getTime()以毫秒为单位返回纪元时间。

You can also use the new Java 8 API也可以使用新的 Java 8 API

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class StackoverflowTest{
    public static void main(String args[]){
        String strDate = "Jun 13 2003 23:11:52.454 UTC";
        DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("MMM dd yyyy HH:mm:ss.SSS zzz");
        ZonedDateTime     zdt  = ZonedDateTime.parse(strDate,dtf);        
        System.out.println(zdt.toInstant().toEpochMilli());  // 1055545912454  
    }
}

The DateTimeFormatter class replaces the old SimpleDateFormat . DateTimeFormatter class 取代了旧的SimpleDateFormat You can then create a ZonedDateTime from which you can extract the desired epoch time.然后,您可以创建一个ZonedDateTime ,您可以从中提取所需的纪元时间。

The main advantage is that you are now thread safe.主要优点是您现在是线程安全的。

Thanks to Basil Bourque for his remarks and suggestions.感谢 Basil Bourque 的发言和建议。 Read his answer for full details.阅读他的答案以获取完整的详细信息。

tl;dr tl;博士

ZonedDateTime.parse( 
                        "Jun 13 2003 23:11:52.454 UTC" , 
                        DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" ) 
                    )
              .toInstant()
              .toEpochMilli()

1055545912454 1055545912454

java.time java.time

This Answer expands on the Answer by Lockni .此答案扩展了 Lockni 的答案

DateTimeFormatter

First define a formatting pattern to match your input string by creating a DateTimeFormatter object.首先通过创建DateTimeFormatter object 来定义格式模式以匹配您的输入字符串。

String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );

ZonedDateTime

Parse the string as a ZonedDateTime .将字符串解析为ZonedDateTime You can think of that class as: ( Instant + ZoneId ).您可以将 class 想象为:( Instant + ZoneId )。

ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );

zdt.toString(): 2003-06-13T23:11:52.454Z[UTC] zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]

现代 java.time 与旧版中的日期时间类类型表。

Count-from-epoch从纪元开始计数

I do not recommend tracking date-time values as a count-from- epoch .我不建议将日期时间值作为从纪元开始的计数。 Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by.这样做会使调试变得棘手,因为人类无法从数字中辨别出有意义的日期时间,因此无效/意外的值可能会溜走。 Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).此外,这些计数在粒度(整秒、毫、微米、纳米等)和纪元(各种计算机系统至少有两打)上也是不明确的。

But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC ( 1970-01-01T00:00:00 ) through the Instant class.但是,如果您坚持,您可以通过Instant class 从 UTC ( 1970-01-01T00:00:00 )的 1970 年第一刻的纪元开始计算毫秒数。 Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.请注意,这意味着数据丢失,因为您将任何纳秒级截断到毫秒级。

Instant instant = zdt.toInstant ();

instant.toString(): 2003-06-13T23:11:52.454Z即时.toString():2003-06-13T23:11:52.454Z

long millisSinceEpoch = instant.toEpochMilli() ; 

1055545912454 1055545912454


About java.time关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .这些类取代了麻烦的日期时间类,例如java.util.DateCalendarSimpleDateFormat

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .规范是JSR 310

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式Joda-Time项目建议迁移到java.time类。

You may exchange java.time objects directly with your database.您可以直接与数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later.使用符合JDBC 4.2或更高版本的JDBC 驱动程序 No need for strings, no need for java.sql.* classes.不需要字符串,不需要java.sql.*类。 Hibernate 5 & JPA 2.2 support java.time . Hibernate 5 & JPA 2.2 支持java.time

Where to obtain the java.time classes?从哪里获得 java.time 课程?

Unfortunately,很遗憾,

the solution provided in all existing answers will fail if you run them on a system with Non-English Locale because the given date-time string is in an English.如果您在具有非英语Locale的系统上运行所有现有答案中提供的解决方案将失败,因为给定的日期时间字符串是英文的。 Never use SimpleDateFormat or DateTimeFormatter without a Locale as they are Locale -sensitive.切勿在没有Locale的情况下使用SimpleDateFormatDateTimeFormatter因为它们对Locale敏感。

The accepted answer uses legacy date-time API which was the correct thing to do using the standard library in 2011 when the question was asked.接受的答案使用遗留日期时间 API,这是在 2011 年提出问题时使用标准库的正确做法。 In March 2014, java.time API supplanted the error-prone legacy date-time API . 2014 年 3 月, java.time API 取代了容易出错的遗留日期时间 API Since then, it has been strongly recommended to use this modern date-time API.从那时起,强烈建议使用这个现代日期时间 API。

Demo using java.time API :演示使用 java.time API

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        long epochMillis = ZonedDateTime.parse(
                    "Jun 13 2003 23:11:52.454 UTC",
                    DateTimeFormatter.ofPattern(
                        "MMM d uuuu HH:mm:ss.SSS z",
                        Locale.ENGLISH
                    )
                )
                .toInstant()
                .toEpochMilli();
        System.out.println(epochMillis);
    }
}

Output : Output :

1055545912454

Learn more about the modern Date-Time API from Trail: Date Time .Trail:Date Time了解有关现代日期时间 API 的更多信息。

Create Common Method to Convert String to Date format创建将字符串转换为日期格式的常用方法

public static void main(String[] args) throws Exception {
    long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
    long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
    long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}

private static long ConvertStringToDate(String dateString, String format) {
    try {
        return new SimpleDateFormat(format).parse(dateString).getTime();
    } catch (ParseException e) {}
    return 0;
}
  String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
   DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
        LocalDateTime zdt  = LocalDateTime.parse(dateTime,dtf);
        LocalDateTime now = LocalDateTime.now();
        ZoneId zone = ZoneId.of("Asia/Kolkata");
        ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
        long a= zdt.toInstant(zoneOffSet).toEpochMilli();
        Log.d("time","---"+a);

you can get zone id form this a link !您可以通过此链接获取区域 ID!

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

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