Javascript compare two datetimes - javascript

I need to compare two datetimes. Format of datetimes is: DD-MM-YYYY hh:mm:ss.
Here is my code:
expirationDate = someDate;
var now = moment().format("DD-MM-YYYY hh:mm:ss");
if(moment(expirationDate).isBefore(now)){
console.log("Past");
} else {
console.log("Future");
}
for this datetimes it work great:
Now: 07-12-2017 11:15:09
Expiration date: 07-12-2017 10:14:10
it return Past
but for this it doesn't work:
Now: 07-12-2017 11:15:03
Expiration date: 15-12-2016 05:59:00
it return Future
I've also tried with if (Date.parse(expireDate) < Date.parse(now)) it also doesn't work properly.
Does anyone know where is the problem or is there any other way to compare two datetimes?

You need to specify the format of the date string.
if (moment().isAfter(moment(expirationDate, 'DD-MM-YYYY HH:mm:ss'))) {
console.log("Past");
} else {
console.log("Future");
}

Related

Can't convert timestamp to date properly in Javascript

I use mongodb as my database and in that db I have a timestamp field but I haven't seen any format similar to that. Some of them are:
1657479170.7300725
1657479170.7301126
1657479170.7301197
1657479170.9120467
1657479170.932398
When i try to convert this to normal date format (YYYY-MM-DD) I get the correct date. For example the converted date of the first timestamp above is:
10.07.2022 21:52:50
However when I try to convert it in javascript I get:
1970-01-20 06:24:39
which is definitely not correct value.
My code for the conversion :
ConvH.forEach(conv => {
conv.tracker.events.forEach(element => {
console.log(parseFloat( parseFloat(element.timestamp.toFixed(4))), moment(new Date( parseFloat( element.timestamp.toFixed(4)))).format("YYYY-MM-DD HH:mm:ss"));
element.timestamp = new Date(element.timestamp).toLocaleString();
})
});
Note : new Date(element.timestamp).toLocaleString(); gives the same thing :/
Try this: new Date(timestamp.getHighBits() * 1000)

How to format a date received from my server using javascript?

I need to format a date with javascript but I'm having a little trouble solving this.
I get two dates, I need to format them and then join the values.
On one of the dates I get this:
"2022-07-12T04:00:00-0300"
And on the other date I get this:
"2022-07-12T06:00:00-0300"
These are always dynamic dates returned from my backend, but here on the frontend I need to display these two dates in this following format:
"04:00 - 06:00"
This is assuming you only need the hours and minutes.
function datesToRange(start, end) {
if (!start || !end) return ""; // If either date is null or undefined.
return start.substring(12, 17) + " - " + end.substring(12, 17);
}
Now you can call this method to get the range in your required format.
E.g.
datesToRange("2022-07-12T04:00:00-0300", "2022-07-12T06:00:00-0300");
Will return "04:00 - 06:00".
You can use slice() method.
var date1 = "2022-07-12T04:00:00-0300";
var date2 = "2022-07-12T06:00:00-0300";
var formatted = `${date1.slice(11, 16)} - ${date2.slice(11, 16)}`;
console.log(formatted);

From date to date validation using javascript

I want to validate from and to date. my date format is d/m/Y H:i
Here is my code:
var startDate = new Date($('#fromdate').val());
var endDate = new Date($('#todate').val());
if (endDate.getTime() <= startDate.getTime()) {
return [false,"To Date cannot be less than From Date"];
}else{
return [true,""];
}
result showing 'Invalid Date'.
Here the date format is different. How to change the date format before passing to Date function?.
You can parse the date string on your own or you can use an external library, like dayjs or momentjs
A simple parsing function could be something like this (assuming the format is the one you mentioned in your question):
function getDateFromCustomFormat(dateString) {
const dateFormatPattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})$/
const parts = dateString.match(dateFormatPattern)
console.log(parts)
const validFormatString = `${parts[3]}-${parts[2]}-${parts[1]} ${parts[4]}:${parts[5]}`
new Date(validFormatString)
}

momentjs for only time value

I use momentjs to work with date and time
let dateAndTime = moment(component.props.data.value, moment.ISO_8601);
let date = '',
time = '';
if (dateAndTime) {
if (moment(dateAndTime, 'YYYY-MM-DD', true).isValid()) {
date = moment(dateAndTime).format('YYYY-MM-DD');
}
if (moment(dateAndTime, 'HH:mm', true).isValid()) {
time = moment(dateAndTime).format('HH:mm');
}
}
this code works just fine if component.props.data.value contains date and time like 2018-05-22 14:45 or if it contains only date like 2018-05-22. The problem is sometimes component.props.data.value contains only time like 14:45, so moment(component.props.data.value, moment.ISO_8601) doesn't create moment object and code below doesn't execute. Is there any way to handle case only for time?
You can use moment(String, String[]), as the docs says:
If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.
This is the same as String + Format, only it will try to match the input to multiple formats.
Your first line of code could be like the following:
let dateAndTime = moment(component.props.data.value, [moment.ISO_8601, 'HH:mm']);

JS Date "Too many Recursions"

I have a piece of code to validate date ranges that Works in Chrome, but not in IE or Firefox.
I am using Kendo DateTimePicker to get the user dates. For example, if DateTo is an earlier date than DateFrom, DateFrom will be automatically change to the same date as DateTo.
if (dateFromEpochTime > dateToEpochTime) {
date = dateFrom.data("kendoDateTimePicker").value();
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
dateTo.kendoDateTimePicker({
value: date,
format: "dd-MM-yyyy HH:mm:ss"
})
changedByCode = true;
}
} else {
if (dateFromEpochTime > dateToEpochTime) {
date = dateTo.data("kendoDateTimePicker").value();
date.setHours(00);
date.setMinutes(00);
date.setSeconds(00);
dateFrom.kendoDateTimePicker({
value: date,
format: "dd-MM-yyyy HH:mm:ss"
})
changedByCode = true;
}
}
This pieces of code that throw the exceptions(Too many recursions for Firefox and Out of stack space for IE) are:
dateTo.kendoDateTimePicker({ value: date, format: "dd-MM-yyyy HH:mm:ss" })
dateFrom.kendoDateTimePicker({ value: date, format: "dd-MM-yyyy HH:mm:ss" })
I cant quite figure out what goes wrong there.
P.s: Before the user presses Ok, I can change the dates as many times as I want and my function will correct them. After I press Ok and try to repeat the action things are breaking. Also, I am not including the same JavaScript file twice.

Categories

Resources