How to convert a date to milliseconds
Solution 1:
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();
Solution 2:
The SimpleDateFormat class allows you to parse a String
into a java.util.Date
object. Once you have the Date object, you can get the milliseconds since the epoch by calling Date.getTime()
.
The full example:
String myDate = "2014/10/29 18:10:45";
//creates a formatter that parses the date in the given format
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long timeInMillis = date.getTime();
Note that this gives you a long
and not a double, but I think that's probably what you intended. The documentation for the SimpleDateFormat
class has tons on information on how to set it up to parse different formats.
Solution 3:
tl;dr
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
Time Zone
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.
java.time
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.
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
.
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?
-
Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- 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
- Much 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.
Joda-Time
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.
ISO 8601
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.
Example Code
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();