How to Convert a String Date to Long Millseconds

How to convert a date to milliseconds

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();

Convert String to Date with Milliseconds

The Date class stores the time as milliseconds, and if you look into your date object you will see that it actually has a time of 1598515567413 milliseconds.

You are fooled by the System.out.println() which uses Date's toString() method. This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.

If you use your formatter, which has milliseconds in its format string, you will see that the milliseconds are correct:

System.out.println(formatter.format(dateFormatter));

outputs 2020-08-27T10:06:07.413

How to convert String time to Long milliseconds in Java

Duration is not the same as Date-Time

Duration is not the same as Date-Time and therefore you should not parse your string into a Date-Time type. The Date-Time type (e.g. java.util.Date) represents a point in time whereas a duration represents a length of time. You can understand it from the following examples:

  1. I have been reading this book for 10 minutes.
  2. I have been reading this book since 4:00 pm.

The first example has a duration whereas the second example has a Date-Time (implicitly today).

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Solution using java.time, the modern Date-Time API:

You can convert your string into ISO 8601 format for a Duration and then parse the resulting string into Duration which you can be converted into milliseconds.

Demo:

import java.time.Duration;

public class Main {
public static void main(String[] args) {
System.out.println(durationToMillis("10:00"));
}

static long durationToMillis(String strDuration) {
String[] arr = strDuration.split(":");
Duration duration = Duration.ZERO;
if (arr.length == 2) {
strDuration = "PT" + arr[0] + "M" + arr[1] + "S";
duration = Duration.parse(strDuration);
}
return duration.toMillis();
}
}

Output:

600000

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

How to convert Date represented as a String to milliseconds?

String someDate = "05.10.2011";
SimpleDateFormat sdf = new SimpleDateFormat("MM.dd.yyyy");
Date date = sdf.parse(someDate);
System.out.println(date.getTime());

How to convert a string Date to long millseconds

Using SimpleDateFormat

String string_date = "12-December-2012";

SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date d = f.parse(string_date);
long milliseconds = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}

Convert String Data Time to long Milliseconds: Scala

Since you have a string you need to specify the format, for available options, see here. I tried to infer your format from your example but it could be that it should be slightly different.

val desiredTime = "3/20/2017 16:5:45"

val format = new java.text.SimpleDateFormat("M/dd/yyyy HH:m:ss")
val time = format.parse(desiredTime).getTime()
print(time)

This will give you 1489997145000 as a result.

android convert date string to time in milliseconds

Use MM for month.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

and to get Time use Date.getTime() method.

for more information take a look at Date and Time Patterns

How to create a long time in Milliseconds from String in Java 8 with LocalDateTime?

You can create DateTimeFormatter with input formatted date and then convert into Instant with zone to extract epoch timestamp

String date = "2019-12-13_09:23:23.333";
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd_HH:mm:ss.SSS");

long mills = LocalDateTime.parse(date,formatter)
.atZone(ZoneId.systemDefault())
.toInstant()
.toEpochMilli();

System.out.println(mills);

How to convert string with this format to Java 8 time and convert to long milliseconds

You may build such pattern using DateTimeFormatterBuilder:

static final DateTimeFormatter DF = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("E MMM dd yyyy HH:mm:ss"))
.appendLiteral(" GMT")
.appendOffset("+HHmm", "+0000")
.optionalStart()
.appendLiteral(" (")
.appendZoneId()
.appendLiteral(')')
.optionalEnd()
.toFormatter()
.withLocale(Locale.US);

Then, just:

String date = "Fri Nov 22 2013 12:12:13 GMT+0000 (UTC)";
long ms = OffsetDateTime.parse(date, DF).toInstant().toEpochMilli(); // 1385122333000


Related Topics



Leave a reply



Submit