I have two dates
var date1="2015-09-18 06:08:50";
var date2="2015-09-18 06:08:51";
I am suffering to get greater one date2.
any body help me.
I have two dates
var date1="2015-09-18 06:08:50";
var date2="2015-09-18 06:08:51";
I am suffering to get greater one date2.
any body help me.
As shows, the inputs are date/time strings with a space between date and time. is right that Date objects and comparison operators work, but the format "YYYY-MM-DD HH:MM:SS" is not guaranteed to parse the same way in all JS engines. A safe pattern is to either convert the string to a standard ISO form first or parse the numeric components and build a Date explicitly.
A quick, reliable approach (turn the space into a "T", check for invalid dates, then compare):
const s1 = '2023-01-02 09:15:30';
const s2 = '2023-01-02 09:15:31';
const d1 = new Date(s1.replace(' ', 'T'));
const d2 = new Date(s2.replace(' ', 'T'));
if (isNaN(d1.getTime()) || isNaN(d2.getTime())) {
// handle parse error
} else if (d1 > d2) {
// d1 is later
} else if (d1 < d2) {
// d2 is later
} else {
// equal
} For full control (no parser ambiguity), split the string into numbers and construct a Date:
function parseYMDHMS(s) {
const [y,m,d,h = 0,min = 0,sec = 0] = s.split(/[- :]/).map(Number);
return new Date(y, m - 1, d, h, min, sec);
} Notes and cautions: comparing Date objects works because they convert to timestamps internally, but always test for invalid dates with isNaN(d.getTime()). ISO strings without a timezone are treated as local time; append Z for UTC. For complex needs or many formats, use a small library like Day.js or Luxon. See MDN for Date parsing and formats: Date — MDN. Thanks also to for the related thread pointer.
Jump to Post— DaveAmour 160If you make then Date objects can you not use comparison operators - eg >, < etc?
If you make then Date objects can you not use comparison operators - eg >, < etc?
Check also this thread:
bye!
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.