Convert a date format in epoch
I have a st开发者_运维问答ring 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?
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.
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.
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]
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?
- Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
- Java 9 brought some minor features and fixes.
- Java SE 6 and Java SE 7
- Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android (26+) bundle implementations of the java.time classes.
- For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
- If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
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.
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!
精彩评论