Convert a date format in epochConvert Date String into Epoch in JavaJava - SimpleDateFormat formatter to return epoch time with millisecondsString (Date and Time) to Unix Timestamp in JavaJava Date timezone printing different timezones for different years, Workaround neededHow can I convert a date in YYYYMMDDHHMMSS format to epoch or unix time?add android calendar events using javaconvert date to timestamp UTCHow to convert a date time string to long (UNIX Epoch Time) in Java 8 (Scala)How to store RSS feeds in Android?Getting milliseconds from Date Time AndroidHow do I read / convert an InputStream into a String in Java?How to print a date in a regular format?Compare two dates with JavaScriptWhere can I find documentation on formatting a date in JavaScript?How do I get the current date in JavaScript?How to split a string in JavaHow to format a JavaScript dateJava string to date conversionConvert UTC Epoch to local dateHow do I convert a String to an int in Java?
If an enemy is just below a 10-foot-high ceiling, are they in melee range of a creature on the ground?
Why is Arya visibly scared in the library in S8E3?
How do you center multiple equations that have multiple steps?
If 1. e4 c6 is considered as a sound defense for black, why is 1. c3 so rare?
How to scale a verbatim environment on a minipage?
Was the ancestor of SCSI, the SASI protocol, nothing more than a draft?
Write to EXCEL from SQL DB using VBA script
Is it cheaper to drop cargo than to land it?
Did we get closer to another plane than we were supposed to, or was the pilot just protecting our delicate sensibilities?
Is balancing necessary on a full-wheel change?
Is Cola "probably the best-known" Latin word in the world? If not, which might it be?
Does higher resolution in an image imply more bits per pixel?
If Melisandre foresaw another character closing blue eyes, why did she follow Stannis?
Disabling Resource Governor in SQL Server
Any examples of headwear for races with animal ears?
Why is Thanos so tough at the beginning of "Avengers: Endgame"?
How can I close a gap between my fence and my neighbor's that's on his side of the property line?
Why are there synthetic chemicals in our bodies? Where do they come from?
Field Length Validation for Desktop Application which has maximum 1000 characters
Was Unix ever a single-user OS?
What happens if I start too many background jobs?
When do aircrafts become solarcrafts?
Unexpected email from Yorkshire Bank
What word means "to make something obsolete"?
Convert a date format in epoch
Convert Date String into Epoch in JavaJava - SimpleDateFormat formatter to return epoch time with millisecondsString (Date and Time) to Unix Timestamp in JavaJava Date timezone printing different timezones for different years, Workaround neededHow can I convert a date in YYYYMMDDHHMMSS format to epoch or unix time?add android calendar events using javaconvert date to timestamp UTCHow to convert a date time string to long (UNIX Epoch Time) in Java 8 (Scala)How to store RSS feeds in Android?Getting milliseconds from Date Time AndroidHow do I read / convert an InputStream into a String in Java?How to print a date in a regular format?Compare two dates with JavaScriptWhere can I find documentation on formatting a date in JavaScript?How do I get the current date in JavaScript?How to split a string in JavaHow to format a JavaScript dateJava string to date conversionConvert UTC Epoch to local dateHow do I convert a String to an int in Java?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
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 datetime date epoch
add a comment |
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 datetime date epoch
add a comment |
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 datetime date 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 datetime date epoch
java datetime date epoch
edited May 19 '16 at 4:35
Ortomala Lokni
24.3k786137
24.3k786137
asked Jul 14 '11 at 1:13
user804979user804979
298138
298138
add a comment |
add a comment |
5 Answers
5
active
oldest
votes
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.
All good but don't throw Exception as such.
– Anirudh
Apr 10 '18 at 12:10
@Anirudhmain
wrapped removed...
– Bohemian♦
Apr 10 '18 at 18:56
add a comment |
You can also use the new 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.
add a comment |
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.
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 adds 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 bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
add a comment |
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;
Don’t swallow exceptions. They have a meaning. Usually an important one.
– Ole V.V.
Jul 19 '17 at 20:30
I recommend staying away from the now long outdated date and time classes likeSimpleDateFormat
. In 2011, when the question was asked, I used them too. Not any more.
– Ole V.V.
Jul 19 '17 at 20:32
add a comment |
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!
1
Thank you for wanting to contribute. It’s not exactly the same question. I getjava.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3
. Finally the correct conversion islong a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();
.
– Ole V.V.
Mar 22 at 12:24
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6687433%2fconvert-a-date-format-in-epoch%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
All good but don't throw Exception as such.
– Anirudh
Apr 10 '18 at 12:10
@Anirudhmain
wrapped removed...
– Bohemian♦
Apr 10 '18 at 18:56
add a comment |
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.
All good but don't throw Exception as such.
– Anirudh
Apr 10 '18 at 12:10
@Anirudhmain
wrapped removed...
– Bohemian♦
Apr 10 '18 at 18:56
add a comment |
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.
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.
edited Apr 10 '18 at 18:54
answered Jul 14 '11 at 1:25
Bohemian♦Bohemian
302k65432575
302k65432575
All good but don't throw Exception as such.
– Anirudh
Apr 10 '18 at 12:10
@Anirudhmain
wrapped removed...
– Bohemian♦
Apr 10 '18 at 18:56
add a comment |
All good but don't throw Exception as such.
– Anirudh
Apr 10 '18 at 12:10
@Anirudhmain
wrapped removed...
– Bohemian♦
Apr 10 '18 at 18:56
All good but don't throw Exception as such.
– Anirudh
Apr 10 '18 at 12:10
All good but don't throw Exception as such.
– Anirudh
Apr 10 '18 at 12:10
@Anirudh
main
wrapped removed...– Bohemian♦
Apr 10 '18 at 18:56
@Anirudh
main
wrapped removed...– Bohemian♦
Apr 10 '18 at 18:56
add a comment |
You can also use the new 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.
add a comment |
You can also use the new 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.
add a comment |
You can also use the new 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.
You can also use the new 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.
edited Apr 12 '17 at 9:53
answered Jun 14 '15 at 13:43
Ortomala LokniOrtomala Lokni
24.3k786137
24.3k786137
add a comment |
add a comment |
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.
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 adds 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 bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
add a comment |
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.
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 adds 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 bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
add a comment |
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.
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 adds 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 bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
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.
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 adds 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 bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
edited Mar 22 at 20:02
answered Oct 6 '16 at 20:21
Basil BourqueBasil Bourque
119k32405566
119k32405566
add a comment |
add a comment |
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;
Don’t swallow exceptions. They have a meaning. Usually an important one.
– Ole V.V.
Jul 19 '17 at 20:30
I recommend staying away from the now long outdated date and time classes likeSimpleDateFormat
. In 2011, when the question was asked, I used them too. Not any more.
– Ole V.V.
Jul 19 '17 at 20:32
add a comment |
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;
Don’t swallow exceptions. They have a meaning. Usually an important one.
– Ole V.V.
Jul 19 '17 at 20:30
I recommend staying away from the now long outdated date and time classes likeSimpleDateFormat
. In 2011, when the question was asked, I used them too. Not any more.
– Ole V.V.
Jul 19 '17 at 20:32
add a comment |
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;
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;
edited Oct 22 '18 at 14:26
Shubham
2,02621528
2,02621528
answered Jun 7 '17 at 6:55
user1960808user1960808
1064
1064
Don’t swallow exceptions. They have a meaning. Usually an important one.
– Ole V.V.
Jul 19 '17 at 20:30
I recommend staying away from the now long outdated date and time classes likeSimpleDateFormat
. In 2011, when the question was asked, I used them too. Not any more.
– Ole V.V.
Jul 19 '17 at 20:32
add a comment |
Don’t swallow exceptions. They have a meaning. Usually an important one.
– Ole V.V.
Jul 19 '17 at 20:30
I recommend staying away from the now long outdated date and time classes likeSimpleDateFormat
. In 2011, when the question was asked, I used them too. Not any more.
– Ole V.V.
Jul 19 '17 at 20:32
Don’t swallow exceptions. They have a meaning. Usually an important one.
– Ole V.V.
Jul 19 '17 at 20:30
Don’t swallow exceptions. They have a meaning. Usually an important one.
– Ole V.V.
Jul 19 '17 at 20:30
I recommend staying away from the now long outdated date and time classes like
SimpleDateFormat
. In 2011, when the question was asked, I used them too. Not any more.– Ole V.V.
Jul 19 '17 at 20:32
I recommend staying away from the now long outdated date and time classes like
SimpleDateFormat
. In 2011, when the question was asked, I used them too. Not any more.– Ole V.V.
Jul 19 '17 at 20:32
add a comment |
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!
1
Thank you for wanting to contribute. It’s not exactly the same question. I getjava.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3
. Finally the correct conversion islong a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();
.
– Ole V.V.
Mar 22 at 12:24
add a comment |
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!
1
Thank you for wanting to contribute. It’s not exactly the same question. I getjava.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3
. Finally the correct conversion islong a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();
.
– Ole V.V.
Mar 22 at 12:24
add a comment |
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!
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!
answered Mar 22 at 8:02
FlashFlash
13
13
1
Thank you for wanting to contribute. It’s not exactly the same question. I getjava.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3
. Finally the correct conversion islong a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();
.
– Ole V.V.
Mar 22 at 12:24
add a comment |
1
Thank you for wanting to contribute. It’s not exactly the same question. I getjava.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3
. Finally the correct conversion islong a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();
.
– Ole V.V.
Mar 22 at 12:24
1
1
Thank you for wanting to contribute. It’s not exactly the same question. I get
java.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3
. Finally the correct conversion is long a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();
.– Ole V.V.
Mar 22 at 12:24
Thank you for wanting to contribute. It’s not exactly the same question. I get
java.time.format.DateTimeParseException: Text '15-3-2019 09:50 AM' could not be parsed at index 3
. Finally the correct conversion is long a = LocalDateTime.parse(dateTime, dtf).atZone(zone).toInstant().toEpochMilli();
.– Ole V.V.
Mar 22 at 12:24
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6687433%2fconvert-a-date-format-in-epoch%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown