1

Tried this:

1.

const today = new Date('28.08.2020');
const milliseconds = today.getTime();
const today = Date.parse("28.08.2020")
var today = new Date('28.08.2020');
var milliseconds = today.getMilliseconds();

Getting NaN while trying to convert a string of date to milliseconds

Hao Wu
  • 17,573
  • 6
  • 28
  • 60
ElMuchacho
  • 300
  • 1
  • 12
  • use Ymd formate as `new Date('2020.08.28')` OR you can use moment js – Devsi Odedra Aug 19 '20 at 09:47
  • @DevsiOdedra—no, don't do that, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Aug 19 '20 at 22:18

5 Answers5

2

Better to change date format to YYYY-MM-DD as suggested in other answer

Or you can do something like this

 var from = '28.08.2020'.split(".");
    var today = new Date(from[2], from[1] - 1, from[0]);
    const milliseconds = today.getTime();

    console.log(milliseconds);
   







   
Devsi Odedra
  • 5,244
  • 1
  • 23
  • 37
1

You use the incorrect format. If you get the date from backend you should convert it.

    const date = '28.08.2020';

    const [day, month, year] = date.split('.');

    const validDate = new Date();

    validDate.setFullYear(year);
    validDate.setDate(day);
    validDate.setMonth(month);

    // or just 
    const validDate2 = new Date(year, month, day);

    const milliseconds = validDate.getTime();
    const milliseconds2 = validDate2.getTime();
    
    console.log(milliseconds)
    console.log(milliseconds2)

    

After this conversion you can use the date as you want

shutsman
  • 2,357
  • 1
  • 12
  • 23
0

Assuming that you do not want to manually parse the string, you could try to use moment library, which allows one to provide custom dateString patterns used for parsing the date, like demonstrated below

const dateString = '28.08.2020';

const date = moment(dateString, "DD.MM.YYYY");

console.log("date", date); // displayed zulu time might be different than your local timezone
console.log("milliseconds", date.valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

Please take a note that moment will accept the date in your local timezone, which may pose some issues. If you want to make up for it, you should look up moment-timezone library

Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
0

Oh, in that case you can change the imput to the "yyyy-mm-dd", is that a posibility?

const date = '28.08.2020';
let dateFromat = date.split('.');
dateFromat = `${dateFromat[2]}-${dateFromat[1]}-${dateFromat[0]}`;
const today = new Date(dateFromat);
const milliseconds = today.getTime();

output: 1598572800000

Juan Luces
  • 29
  • 7
-2

the dating format is wrong.

new Date('2020-08-28') should work

Juan Luces
  • 29
  • 7