转换以纪元为单位的日期格式

发布于 2024-11-24 05:33:57 字数 132 浏览 3 评论 0 原文

我有一个带有日期格式的字符串,例如

Jun 13 2003 23:11:52.454 UTC

包含毫秒...我想在纪元中转换它。 Java 中是否有一个实用程序可以用来进行此转换?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

如梦 2024-12-01 05:34:36
  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);

您可以通过此链接获取区域ID

  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!

陈年往事 2024-12-01 05:34:35

创建将字符串转换为日期格式的通用方法

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;
}

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;
}
旧街凉风 2024-12-01 05:34:34

太长了;博士

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

1055545912454

java.time

此答案扩展了 Lockni 的答案

DateTimeFormatter

首先通过创建 DateTimeFormatter 对象。

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

ZonedDateTime

将字符串解析为 ZonedDateTime。您可以将该类视为:( Instant + ZoneId )。

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

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

Table of types of date-time classes in modern java.time versus legacy.

Count-from-epoch

我不建议将日期时间值作为 count-from-纪元。这样做会使调试变得棘手,因为人类无法从数字中辨别出有意义的日期时间,因此无效/意外的值可能会溜走。而且,这样的计数在粒度(整秒、毫秒、微米、纳等)和纪元(各种计算机系统中至少有两打)上都是不明确的。

但如果您坚持,您可以通过 即时 班级。请注意,这意味着数据丢失,因为您将任何纳秒截断为毫秒。

Instant instant = zdt.toInstant ();

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

long millisSinceEpoch = instant.toEpochMilli() ; 

1055545912454


关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧遗留日期时间类,例如java.util.Date, 日历, & SimpleDateFormat

要了解更多信息,请参阅 Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范为 JSR 310

Joda-Time 项目,现已在 维护模式,建议迁移到java.time< /a> 类。

您可以直接与数据库交换java.time对象。使用符合 JDBC 驱动程序 /jeps/170" rel="nofollow noreferrer">JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类。 Hibernate 5 和 Hibernate 5 JPA 2.2 支持 java.time。

从哪里获取 java.time 类?

tl;dr

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

1055545912454

java.time

This Answer expands on the Answer by Lockni.

DateTimeFormatter

First define a formatting pattern to match your input string by creating a 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. You can think of that class as: ( Instant + ZoneId ).

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

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

Table of types of date-time classes in modern java.time versus legacy.

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. 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

long millisSinceEpoch = instant.toEpochMilli() ; 

1055545912454


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

梦里兽 2024-12-01 05:34:34

不幸的是,

如果您在非英语 Locale 的系统上运行所有现有答案中提供的解决方案,它们将会失败,因为给定的日期时间字符串是英语。 切勿在没有区域设置的情况下使用SimpleDateFormatDateTimeFormatter< /a> 因为它们是区域设置敏感的。

接受的答案使用旧版日期时间 API,这是 2011 年使用标准库时的正确做法,当时问题是问道。 2014 年 3 月,java.time API 取代了 容易出错的旧版日期时间 API。从那时起,强烈建议使用这个现代日期时间 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);
    }
}

输出

1055545912454

跟踪:日期时间

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. Never use SimpleDateFormat or DateTimeFormatter without a Locale as they are Locale-sensitive.

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. In March 2014, java.time API supplanted the error-prone legacy date-time API. Since then, it has been strongly recommended to use this modern date-time API.

Demo using 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:

1055545912454

Learn more about the modern Date-Time API from Trail: Date Time.

幽蝶幻影 2024-12-01 05:34:33

您还可以使用 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  
    }
}

DateTimeFormatter 类替换了旧的 SimpleDateFormat。然后,您可以创建一个 ZonedDateTime 您可以从中提取所需的纪元时间。

主要优点是您现在是线程安全的。

感谢 Basil Bourque 的评论和建议。阅读他的回答以获取完整详细信息。

You can also use the 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. You can then create a ZonedDateTime from which you can extract the desired epoch time.

The main advantage is that you are now thread safe.

Thanks to Basil Bourque for his remarks and suggestions. Read his answer for full details.

鲜肉鲜肉永远不皱 2024-12-01 05:34:32

此代码显示如何使用 java.text.SimpleDateFormat< /a> 解析 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() 返回纪元时间(以毫秒为单位)。

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文