27

Given that I have: mm, dd, yy, hh:mm, am/pm, what is the recommended/easiest way to convert that data into milliseconds from epoch?

alex
  • 479,566
  • 201
  • 878
  • 984
deruse
  • 2,851
  • 7
  • 40
  • 60

5 Answers5

34

Everytime I get an upvote on this answer, I'm reminded that my answer doesn't actually answer the question.

OP: If you can parse your string into the following format, you can use one of the other answers. MM/DD/YYYY HH:MM:SS AM EDT (It's important to specify the timezone; epoch is based on the meridian)

let milliseconds = new Date("1/20/1982 5:00 PM EST").getTime()
console.log(milliseconds);

Original Answer that some people have found useful: Another technique (which most browsers support, as well as NodeJS) that doesn't require having to instantiate a Date object

var nowEpoch = Date.now();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Chris
  • 2,045
  • 1
  • 18
  • 21
22
new Date("some string").getTime()
josh3736
  • 139,160
  • 33
  • 216
  • 263
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
3

You can get the milliseconds from epoch with +new Date('date string').

jsFiddle.

The + operator implicitly calls valueOf() which returns the same as getTime().

alex
  • 479,566
  • 201
  • 878
  • 984
0
var date;

if(pm)
    date = new Date(yy, mm, dd, hh+12, mm, 0, 0);
else
    date = new Date(yy, mm, dd, hh, mm, 0, 0);

var millis = date.getTime();
var seconds = millis/1000;
Cai
  • 1,726
  • 2
  • 15
  • 24
Joseph Dailey
  • 4,735
  • 2
  • 15
  • 18
0

var myDate = new Date(Timestamp); // Your timezone! either timestamp ot date var myEpoch = myDate.getTime()/1000.0;

Murthii Ch
  • 29
  • 1
  • 2