Comparing date and time with moment js - javascript

In my react app I am receiving an endDate, and also separately receiving an endTime. I have to check if that endDate and endTime are before the current date and time.
let endDate = "04/13/2022";
let endTime = "22:00"
console.log(moment(endDate, "MM/DD/YYYY", endTime).isBefore(moment());
//true
Today's date is the same as the endDate but the time is earlier than the endTime so I should see False instead of true. The times are not being compared. Does anyone know how to resolve this?

Combine the date and time strings, and parse as one full date-time string.
const endDate = '04/13/2022';
const endTime = '22:00';
const date = moment(`${endDate} ${endTime}`, 'MM/DD/YYYY HH:mm');
console.log(date.isBefore(moment())); // false
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>

Related

Time changes after toLocaleTimeString()

I'm using a google sheets script, which on the click of a button will add values to two fields.
The first will contain the date, the second the time.
For this, I use this piece of code:
var timestamp = new Date();
var date = Utilities.formatDate(timestamp, "GMT+1", "dd/MM/yyyy");
var time = timestamp.toLocaleTimeString('nl-BE');
Now, the issue is that the time is off by 6 hours.
The timestamp value does contain the correct time, the date variable gets the correct date, but the time seems to differ 6 hours after the 'toLocaleTimeString() function.
Use Utilities.formatDate() for time as well, like this:
const timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); // or 'GMT+1'
const timestamp = new Date();
const dateString = Utilities.formatDate(timestamp, timezone, 'dd/MM/yyyy');
const timeString = Utilities.formatDate(timestamp, timezone, 'HH:mm:ss');
console.log(`date and time in ${timezone}: ${dateString} ${timeString}`);

How to check if date is a current date with using dayjs?

I have a problem with checking if my date in unix is a current date with using dayjs library, I try like below:
const date = 1631978008; //today: 2021-09-18
const isToday = dayjs().isSame(date, 'day'); //return false
but always return me false when my date is a today date, can someone tell me why? it should return true :/
thanks for any help!
You can use the unix function to parse the unix timestamp in seconds before comparing it with the current time.
const date = 1631978008; //today: 2021-09-18
const isToday = dayjs().isSame(dayjs.unix(date), 'day');
console.log(isToday);
<script src="https://unpkg.com/dayjs#1.8.21/dayjs.min.js"></script>

How to prevent changes on timestamp when convert from string to ISODate Javascript?

I have a date in (yyyy-mm-dd) format, i want to get start and end date with timestamps and ISO format, i can concat date and timestamp but i want it in date type not in string,
let date = "2020-09-11";
Expected result should be,
startDate = 2020-09-11T00:00:00.000Z
endDate = 2020-09-11T23:59:59.000Z
The start date is correct, The end date is not correct, it gives different time stamp, 18:29:59.000Z when i set it to setHours(23,59,59),
let startDate = new Date(date);
console.log(startDate);
// output: 2020-09-11T00:00:00.000Z
let endDate = new Date(new Date(date).setHours(23,59,59));
console.log(endDate);
// output: 2020-09-11T18:29:59.000Z
I looked at this question convert string to ISO date time in nodejs, but this does not help me, i don't want to use moment,
Am i doing wrong to convert dates? i am using nodejs.
You should use setUTCHours()
The setUTCHours() method sets the hour for a specified date according to universal time
let date = new Date()
let startDate = new Date(new Date(date).setUTCHours(0,0,0));
let endDate = new Date(new Date(date).setUTCHours(23,59,59));
console.log(startDate);
console.log(endDate);
You could just add the postfix without conversion to a local date.
let date = "2020-09-11",
startDate = date + 'T00:00:00.000Z',
endDate = date + 'T23:59:59.000Z';
console.log(startDate);
console.log(endDate);

How to convert the DD-MM-YYYY HH:mm format to epoch time using moment or js?

I have a date time picker and it omits date in format of a DD-MM-YYYY HH:mm a format. I want to convert it into epoch time to store it in the database backend.
I have tried using the following methods so far, but all of them return NaN as output:
var loadingPlannedUnTime = this.state.loadingPlannedUnTime;
console.log("normal conversion"+loadingPlannedUnTime);
//returns 9-08-2020 15:08:00
//Moment method
var loadingPlannedUnTime = moment(this.state.loadingPlannedUnTime).unix();
console.log("moemnt"+loadingPlannedUnTime)
//Returns NaN
//JS getTime() method
var pickupDateTime = new Date(this.state.loadingPickupTime);
var loadingPickupTime = pickupDateTime.getTime();
console.log("new date and gettime"+loadingPickupTime)
//Returns NaN
What is the correct method to convert it to epoch time?
https://momentjs.com/docs/
If you know the format of an input string, you can use that to parse a moment.
moment("12-25-1995", "MM-DD-YYYY");
const x = moment('24-12-2019 09:15', "DD-MM-YYYY hh:mm");
console.log(x.format())
<script src="https://rawgit.com/moment/moment/2.2.1/min/moment.min.js"></script>
const matches = loadingPlannedUnTime.match(/(\d{1,2})-(\d{1,2})-(\d{2,4}) (\d{1,2}):(\d{1,2}):(\d{1,2})/);
if (!!matches) {
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
const epoch = new Date(matches[3], matches[2] - 1, matches[1], matches[4], matches[5], matches[6]).getTime();
console.log(epoch);
}

Javascript Date Comparison not behaving as expected

I am getting a SQL date - NOT datetime - object pushed into my Javascript code, and I need to see whether it's before today or not. Here is the code I have (the relevant part):
todaysDate = new Date();
todaysDate.setHours(0,0,0,0);
var date = Date.parse(row[3]);
// date.setHours(0,0,0,0);
if (date < todaysDate) {
alert("date is before today");
dueDate = '<small class="text-danger">';
} else {
alert("date is after today");
dueDate = '<small class="text-muted">';
}
row[3] is the source of the SQL date. So, this works fine for everything except dates that are today. Without the commented line, it thinks that anything with today's date is in the past. With the commented line, my code breaks. Any thoughts as to how to fix this? Not sure what I'm doing wrong.
Thanks!
If your date string is like "2016-04-10" and your time zone is west of GMT, say -04:00, then in browsers compliant with ECMAScript 2016 you will get a Date for "2016-04-09T19:00:00-0400".
When you create a Date using new Date() and set the hours to zero (assuming it's 10 April where you are), you'll get a Date for "2016-04-10T00:00:00-0400".
So when compared they have different time values.
What you need is to either treat the string you get from the database as local, or get the UCT date where you are, so:
var dateString = '2016-04-10';
var parsedDate = new Date(dateString);
var todayUTCDate = new Date();
todayUTCDate.setUTCHours(0,0,0,0);
document.write(parsedDate + '<br>' + todayUTCDate);
But not all browsers parse strings according to ECMAScript 2015 so they should always be manually parsed. Use a library, or write a small function, e.g.
// Parse date string in format 'yyyy-mm-dd' as local date
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2]);
}
and replace:
var date = Date.parse(row[3]);
with:
var date = parseISOLocal(row[3]);
and then in the comparison, compare the time values:
if (+date < +todaysDate) {
or
if (date.getTime() < todaysDate.getTime()) {
Use getTime() of date object.
The getTime() method returns the number of milliseconds between midnight of January 1, 1970 and the specified date.
You can compare miliseconds and do your operations
date.getTime() > todaysDate.getTime()
Also be sure that Date.parse is returning a valid date.

Categories

Resources