Home > Enterprise >  Convert string to date in JavaScript to allow comparison
Convert string to date in JavaScript to allow comparison

Time:10-11

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 timestamp so I can compare between the dates?

CodePudding user response:

You can create the timestamp by using the getTime() method, but to do so, you firstly need to create a JavaScript date object which will allow to use the method.

The problem with your inputs is that their format is not compatible with the new Date() method to create the object in the first place, so I use the slice() method to change the format of your date and time variables to do all of the above.

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

// Changing format
var year = date.slice(6,10),month = date.slice(3,5),day = date.slice(0,2),slice1 = time.slice(0,5),slice2 = time.slice(5,13), newTime = slice1   ":"   slice2;

// Creating a Date object
const newDate = new Date(year   "-"   month   "-"   day   "T"   newTime); 

// Seconds since 1970/01/01
var seconds = newDate.getTime() / 1000; 

console.log("Timestamp: "   seconds);

CodePudding user response:

The Date.prototype.toISOString method converts date objects to an easy-to-compare format:

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`
  • Related