I want to convert String myDate = "2014/10/29 18:10:45"
to
long ms (i.e. currentinmlilies)
? I look for it on Google, but I can only find how to convert ms to date.
Note: To make it clear, I want to get the ms from the date in 1970/1/1 format.
Select a timestamp type in the Type group box. If you need to display milliseconds, instead of clicking the Date category, select Custom, and then enter dd-mmm-yyyy hh:mm:ss. 000 in the Type field.
A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .
In the Format Cells window, go to the Number tab, select Custom from the Category list, and enter h:mm:ss. 000 in the Type text box. As a result, all of the time values are displayed with milliseconds as decimals.
You don't have a Date
, you have a String
representation of a date. You should convert the String
into a Date
and then obtain the milliseconds. To convert a String
into a Date
and vice versa you should use SimpleDateFormat
class.
Here's an example of what you want/need to do (assuming time zone is not involved here):
String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();
Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.
Using the new Date/Time API available since Java 8:
String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
With this new Date/Time API, when using a date, you need to
specify the Zone where the date/time will be used. For your case,
seems that you want/need to use the default zone of your system.
Check which zone you need to use for specific behaviour e.g.
CET or America/Lima
*/
long millis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli();
LocalDateTime.parse( // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
"2014/10/29 18:10:45" // Convert input string to comply with standard ISO 8601 format.
.replace( " " , "T" ) // Replace SPACE in the middle with a `T`.
.replace( "/" , "-" ) // Replace SLASH in the middle with a `-`.
)
.atZone( // Apply a time zone to provide the context needed to determine an actual moment.
ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjust into UTC.
.toEpochMilli() // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.
1414602645000
The accepted answer is correct, except that it ignores the crucial issue of time zone. Is your input string 6:10 PM in Paris or Montréal? Or UTC?
Use a proper time zone name. Usually a continent plus city/region. For example, "Europe/Oslo"
. Avoid the 3 or 4 letter codes which are neither standardized nor unique.
The modern approach uses the java.time classes.
Alter your input to conform with the ISO 8601 standard. Replace the SPACE in the middle with a T
. And replace the slash characters with hyphens. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
A LocalDateTime
, like your input string, lacks any concept of time zone or offset-from-UTC. Without the context of a zone/offset, a LocalDateTime
has no real meaning. Is it 6:10 PM in India, Europe, or Canada? Each of those places experience 6:10 PM at different moments, at different points on the timeline. So you must specify which you have in mind if you want to determine a specific point on the timeline.
ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Now we have a specific moment, in that ZonedDateTime
. Convert to UTC by extracting a Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = zdt.toInstant() ;
Now we can get your desired count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.
long millisSinceEpoch = instant.toEpochMilli() ;
Be aware of possible data loss. The Instant
object is capable of carrying microseconds or nanoseconds, finer than milliseconds. That finer fractional part of a second will be ignored when getting a count of milliseconds.
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
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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?
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.
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I will leave this section intact for history.
Below is the same kind of code but using the Joda-Time 2.5 library and handling time zone.
The java.util.Date, .Calendar, and .SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the java.time package (inspired by Joda-Time) built into Java 8.
Your string is almost in ISO 8601 format. The slashes need to be hyphens and the SPACE in middle should be replaced with a T
. If we tweak that, then the resulting string can be fed directly into constructor without bothering to specify a formatter. Joda-Time uses ISO 8701 formats as it's defaults for parsing and generating strings.
String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With