I have multiple date's for example(25-12-2017) i need them to be converted to milliseconds by javascript
Asked
Active
Viewed 2.0k times
3 Answers
10
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());
Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Eddie
- 26,593
- 6
- 36
- 58
-
Ok, but why doesn't the *prepareDate* function just return a Date? – RobG Mar 13 '18 at 07:26
3
var dateTokens = "2018-03-13".split("-");
//creating date object from specified year, month, and day
var date1 = new Date(dateTokens[0], dateTokens[1] - 1, dateTokens[2]);
//creating date object from specified date string
var date2 = new Date("2018-03-13");
console.log("Date1 in milliseconds: ", date1.getTime());
console.log("Date2 in milliseconds: ", date1.getTime());
console.log("Date1: ", date1.toString());
console.log("Date2: ", date2.toString());

Muhammad Usman
- 863
- 1
- 11
- 18
-
Note that the time value returned for the two approaches is different by your timezone offset (there's an error in your code). Don't use the built-in parser. – RobG Mar 13 '18 at 07:23
1
In addition to using vanilla javascript, you can also use many libraries to get more functions.
For example, use moment.js you can convert date to milliseconds by moment('25-12-2017', 'DD-MM-YYYY').valueOf()
, more elegant and powerful than vanilla javascript.

Harry Yu
- 323
- 1
- 3
- 11
-
See [*How do I write a good answer?*](https://stackoverflow.com/help/how-to-answer) In particular, an answer should answer the question per the section *Answer the question*. Imagine asking a question about how to do something in the DOM in plain script and all you get are answers like "use a library like jQuery or Prototype.js" or "use a framework like react or angular". – RobG Mar 26 '18 at 13:10