How to Convert a Date to Milliseconds

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 iso date to milliseconds in javascript

Try this

var date = new Date("11/21/1987 16:00:00"); // some mock datevar milliseconds = date.getTime(); // This will return you the number of milliseconds// elapsed from January 1, 1970 // if your date is less than that date, the value will be negative
console.log(milliseconds);

Convert python datetime to timestamp in milliseconds

In Python 3 this can be done in 2 steps:

  1. Convert timestring to datetime object
  2. Multiply the timestamp of the datetime object by 1000 to convert it to milliseconds.

For example like this:

from datetime import datetime

dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000

print(millisec)

Output:

1482223122760.0

strptime accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime object. The format string (second argument) specifies the actual format of the string that you have passed.

Here is the explanation of the format specifiers from the official documentation:

  • %d - Day of the month as a zero-padded decimal number.
  • %m - Month as a zero-padded decimal number.
  • %Y - Year with century as a decimal number
  • %H - Hour (24-hour clock) as a zero-padded decimal number.
  • %M - Minute as a zero-padded decimal number.
  • %S - Second as a zero-padded decimal number.
  • %f - Microsecond as a decimal number, zero-padded to 6 digits.

How to convert date to milliseconds with out timezone offset?

For a difference of 0 from UTC:

    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MMM dd, uuuu", Locale.ENGLISH);
String selectedDate = "Jan 18, 2020";
ZonedDateTime zdt = LocalDate.parse(selectedDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC);
System.out.println(zdt);
long millisSinceEpoch = zdt.toInstant().toEpochMilli();
System.out.println(millisSinceEpoch);

Output from this snpipet is:

2020-01-18T00:00Z
1579305600000

I am using java.time, the modern Java date and time API. The classes that you used, SimpleDateFormat and Date, are poorly designed and long outdated, and no one should use them anymore.

Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • Java Specification Request (JSR) 310, where java.time was first described.
  • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
  • ThreeTenABP, Android edition of ThreeTen Backport
  • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

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 date to milliseconds by javascript?

One way is to use year, month and day as parameters on new Date

new Date(year, month [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

You can prepare your date string by using a function.

Note: Month is 0-11, that is why m-1

Here is a snippet:

function prepareDate(d) {  [d, m, y] = d.split("-"); //Split the string  return [y, m - 1, d]; //Return as an array with y,m,d sequence}
let str = "25-12-2017";let d = new Date(...prepareDate(str));
console.log(d.getTime());

How to convert date format to milliseconds?

long millisecond = beginupd.getTime();

Date.getTime() JavaDoc states:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.

Convert Date-Time to Milliseconds - C++ - cross platform

Given the format of your string, it is fairly easy to parse it as follows (although a regex or get_time might be more elegant):

tm t;
t.tm_year = stoi(s.substr(0, 4));
t.tm_mon = stoi(s.substr(4, 2));
t.tm_mday = stoi(s.substr(6, 2));
t.tm_hour = stoi(s.substr(9, 2));
t.tm_min = stoi(s.substr(12, 2));
t.tm_sec = 0;
double sec = stod(s.substr(15));

Finding the time since the epoch can be done with mktime:

mktime(&t) + sec * 1000

Note that the fractional seconds need to be handled differently - unfortunately, tm has only integer seconds.

(See the full code here.)


Edit

As Mine and Panagiotis Kanavos correctly note in the comments, Visual C++ apparently supports get_time for quite a while, and it's much shorter with it (note that the fractional seconds need to be handled the same way, though).



Related Topics



Leave a reply



Submit