Convert a date format in epoch
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.
Convert from format date string to unix (epoch) time value
To convert the string into an array of integers, look into split('/')
, to turn that into a unix time stamp look here (you probably want to_i
but be warned that it incorporates your local time zone).
Javascript Convert Date Time string to Epoch
JavaScript dates are internally stored as milliseconds since epoch. You just need to convert it to a number, e.g. with the unary +
operator, to get them. Or you can use the .getTime
method.
The harder will be parsing your date string. You likely will use a regex to extract the values from your string and pass them into Date.UTC
:
var parts = datestring.match(/(\d{2})\/(\d{2})\/(\d{4}) (\d{2}):(\d{2})/);
return Date.UTC(+parts[3], parts[2]-1, +parts[1], +parts[4], +parts[5]);
This will yield 1354604400000 ms
for your example date.
Java Converting date to epoch value produces false output
The issue is that you're not dealing with a unix timestamp when calling getTime()
in Java. Unix timestamps are expressed in seconds since the epoch, while the values you're getting from Java are milliseconds since the epoch (Jan 01 1970), hence the difference.
It would have to be:
epoch = datenew.getTime() / 1000;
This should get you at least a couple of 10000 years closer. If you still see a difference after that, it's timezone-related, and can be accommodated for by specifying the timezone on your DateFormat
instance.
PHP - Convert date and time into Epoch
Use strtotime function
echo strtotime("11/22/2018 01:16:14 AM");
How do I convert this time format into epoch in java? Tue Dec 28 16:55:00 GMT+05:30 2021 to Epoch
Alternative solution with java.time.OffsetDateTime
Here's an alternative solution that makes use of java.time
keeping all the information of the input String
:
public static void main(String[] args) throws IOException {
// input
String dpDate = "Tue Dec 28 16:55:00 GMT+05:30 2021";
// define a formatter with the pattern and locale of the input
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
// parse the input to an OffsetDateTime using the formatter
OffsetDateTime odt = OffsetDateTime.parse(dpDate, dtf);
// receive the moment in time represented by the OffsetDateTime
Instant instant = odt.toInstant();
// extract its epoch millis
long epochMillis = instant.toEpochMilli();
// and the epoch seconds
long epochSeconds = instant.getEpochSecond();
// and print all the values
System.out.println(String.format("%s ---> %d (ms), %d (s)",
odt, epochMillis, epochSeconds));
}
Output:
2021-12-28T16:55+05:30 ---> 1640690700000 (ms), 1640690700 (s)
A LocalDateTime
should not be used here, because you may lose the information about the offset and a ZonedDateTime
can neither be used due to the input lacking information about a zone like "Asia/Kolkata"
or "America/Chicago"
, it just provides an offset from UTC.
If you simply want to get the epoch millis, you can write a short method:
// define a constant formatter in the desired class
private static final DateTimeFormatter DTF_INPUT =
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO uuuu", Locale.ENGLISH);
…
/**
* parses the input, converts to an instant and returns the millis
*/
public static long getEpochMillisFrom(String input) {
return OffsetDateTime.parse(input, DTF_INPUT)
.toInstant()
.toEpochMilli();
}
Java - SimpleDateFormat formatter to return epoch time with milliseconds
You have a simple error in the use of case in your format pattern string (these are case sensitive). And worse, you are using the old and troublesome SimpleDateFormat
class. One of the many problems with it is it’s not telling you what the problem is.
So I recommend you use the modern Java date and time API instead (I am deliberately using your format pattern string verbatim):
String receivedTimetamp = "2017.07.19 11:42:30:423";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:sss");
LocalDateTime dateTime = LocalDateTime.parse(receivedTimetamp, parseFormatter);
System.out.println(dateTime);
This code throws an IllegalArgumentException: Too many pattern letters: s
. I hope this calls your awareness to the fact that you are using two s’s for seconds and three s’s for fraction of second. If it still isn’t clear, the documentation will tell you that lowercase s
is correct for seconds, while you need uppercase S
for the fraction. Let’s repair:
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss:SSS");
Now the code prints 2017-07-19T11:42:30.423
, so we have managed to parse the string correctly.
To convert to milliseconds we are still missing a crucial piece of information: in what time zone should the timestamp be interpreted? I think the two obvious guesses are UTC and your local time zone (which I don’t know). Try UTC:
System.out.println(dateTime.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli());
This produces 1500464550423
, which is the number you asked for. I suppose we’re done.
If you wanted your JVM’s time zone setting instead, use .atZone(ZoneId.systemDefault())
instead of .atOffset(ZoneOffset.UTC)
, but beware that the setting may be altered by other software running in the same JVM, so this is fragile.
Related Topics
How to Set Classpath When I Use Javax.Tools.Javacompiler Compile the Source
Composing Swing Components: How to Add the Ability to Add Actionlisteners
Printing My MAC's Serial Number in Java Using Unix Commands
How to Define Multiple Jbutton Actions from a Different Class
How to Read Properties File in Web Application
(Unknown Source) in Exception Stack Trace
What Are the Best Use Cases for Akka Framework
How to Pause and Resume a Thread in Java from Another Thread
Difference Between Role and Grantedauthority in Spring Security
How to Determine If a List Is Sorted in Java
Cannot Change Version of Project Facet Dynamic Web Module to 3.0
Double Calculation Producing Odd Result
Best Way to Build a Plugin System with Java
Java Regex for Support Unicode
In Which Case Do You Use the JPA @Jointable Annotation
How to Use Yamlpropertiesfactorybean to Load Yaml Files Using Spring Framework 4.1