Home > Enterprise >  Convert string to date in javascript to allow comparision
Convert string to date in javascript to allow comparision

Time:10-10

I have two variables, a date and a time

let date = "30.09.2021";
let time = "13:2224.990";

how I can convert that to a time stamp so I can compare between the dates?

CodePudding user response:

ISO 8601 standard defines an easy-to-compare format for dates:

const date1 = new Date();
const date2 = new Date();

date1.toISOString() < date2.toISOString();
// `true` if `date1` is earlier than `date2`
// `false` if `date1` is later than or equal to `date2`

CodePudding user response:

let date = "30.09.2021", time ="13:2224.990";

var year = date.slice(6,10), month = date.slice(3,5), day = date.slice(0,2);

var slice1 = time.slice(0,5), slice2 = time.slice(5,13);

var newTime = slice1   ":"   slice2;

var newDate = new Date(year   "-"   month   "-"   day   "T"   newTime);
var seconds = newDate.getTime() / 1000; 

console.log("Timestamp: "   seconds);

  • Related