How to Compare Date time in moment js - javascript

Hi I need to validate two date time moment instances,
Using this Package to get time we can select hour min sec in this.
I need validate if selected Date time is after or before like you see in code .I'm having confusion will it validate date with time ?
How to compare selected date time hour min sec in isAfter/isBefore
function DateValidate(selectedDate,type){ //selected date in moment instance
let isValid=false
const {startTime,endTime}=dateTime // from state
if(type==='start'&& endTime){
isValid=selectedDate.isAfter(endTime);
}else if(type==='end'&& startTime){
isValid=selectedDate.isBefore(startTime);
}
return isValid
}
should i need to format selected date needed format -(dd/mm/yyyy hh:mm:ss) and then apply isBefore/isafter ?
Please help...

Yes it will validate date along with the time. Here is the code which shows the 1 second difference between two dates.
const out = document.getElementById('output');
const today = moment();
var afterToday;
setTimeout(()=>{
afterToday = moment();
}, 1000)
setTimeout(()=>{
//const diff = afterToday.isAfter(today);
const diff = today.isAfter(afterToday);
out.innerText = diff;
}, 2000)
To see it in action take a look here.

It looks like, in your example, the selectedDate is not a valid moment object. selectedDate needs to be a valid moment object in order to successfully apply the isAfter() and isBefore() methods, and startTime and endTime must also be in the correct format. See the examples in the docs: https://momentjs.com/docs/#/query/is-after/.
If you know the format ahead of time, you can pass that as the second argument into moment(). See the relevant part of the docs: momentjs.com/docs/#/parsing/string-format. In your example, something like moment("10/09/1997 02:31:01", "dd/mm/yyyy hh:mm:ss")

Related

How can I combine the output of a date picker and time selector to make a single date.toISOString in JavaScript?

I have a date selector and a time selector, and I'm trying to figure out how I can combine their outputs to make a single ISOString so that I can use with the google calendar API.
Here's what I've tried:
//date = 2022-05-18
//time = 14:22
const apptdate = new Date(date)
const timeSplit = time.split(':')
apptDate.setHours(timeSplit[0])
apptDate.setMinutes(timeSplit[1])
What I notice is when I console.log(apptdate) this is the output I get: 2022-05-17T18:22:00.000Z
I'm not sure why it changes the day from May 18 to May 17, and the time from 14:22 to 18:22.
Does anyone have a solution for this? Or even a completely different way of combining date and time to one string (other than using a datetime-local input format, I want to keep the date and time separate in my database).
"2022-05-18" is parsed as UTC but apptDate.setHours(timeSplit[0]) sets the local hour. So if the host has a negative offset, the local date is 17 May and the time is set to the local hour on 17 May, not UTC hour on 18 May.
Instead use setUTCHours and setUTCMinutes.
let date = '2022-05-18';
let time = '14:22';
let apptDate = new Date(date);
let timeSplit = time.split(':');
apptDate.setUTCHours(timeSplit[0]);
apptDate.setUTCMinutes(timeSplit[1]);
// 2022-05-18T14:22:00.000Z
console.log(apptDate.toISOString());
PS. There was also a typo: let apptdate then later apptDate.

How to add time to a date in js

I get a date with string type from API and then I parse it to a date type so that I can use it for a count down.
I want to add 30 days to the date that I've got from API.
Here is the code that I parsed
const time = Date.parse("2020-12-30T18:35:43");
I've already read this question and I tried to implement it
Add 10 seconds to a Date
but react does not recognize the getDate
if you need more information, please let me know
You need to wrap your parsed date with a new Date()
const time = new Date(Date.parse("2020-12-30T18:35:43"));
// As mention by other comments, this is enough
// const time = new Date("2020-12-30T18:35:43");
time.setSeconds(time.getSeconds() + 10) // 1609349753000
setSeconds and getSeconds are method of the Date, you was trying to execute them on a number.
EDIT :
Answer can be found here
In a general way you should use date-fns for date manipulations ;)
you can also setDate to your existing date. Check following code.
const date = new Date("2020-12-30T18:35:43");
date.setDate(date.getDate() + 30);

moment js change the date portion of a datetime

Using the moment.js library say i have a datetime with today's date and i would like to replace only the date part of the datetime with another value and keep the time portion the same
I don't want to subtract or add days etc - i have a 3rd party time picker that when you select a time it creates a datetime that is always the current day. I need to send back to server a different datetime - the date is different but keep the time portion from the picker.
example code:
let myDate = "2019-03-15T00:00:00"
let selectedDateTime = "2019-04-04T12:30:00"
expected result would be:
"2019-03-15T12:30:00"
Thank you
The following should solve your problem:
let myDate = moment("2019-03-15T00:00:00")
let selectedDateTime = moment("2019-04-04T12:30:00")
selectedDateTime.date(myDate.date());
selectedDateTime.month(myDate.month());
selectedDateTime.year(myDate.year());
As #JeremyThille suggested, you should take a look at the documentation.

JavaScript date displaying the wrong day and time

I have this application where I want to use you date, but the problem is that the date is not working as I expect.
I create a date object like this:
// Get today's date
today: function () {
// Create a new date
var date = new Date();
// Set to midnight
date.setHours(0, 0, 0, 0);
// Return our date
return date;
},
and If I output that date in my view I get yesterdays date at 23:00 hours....
Which looks like this:
2015-07-08T23:00:00.000Z
Does anyone know how I can get the date to be formatted properly?
Update
Just to elaborate a bit, I want to use the date to compare against records in the database. These records have the date applied to them, because the JavaScript is showing the local date time, it is not comparing correctly. Also there is a case where I am saving that date and I don't want it to save the local date.
based on your culture setting you can use the
date.toLocaleDateString()
this will give localized string format back
date.toUTCString();
date.toLocaleString();
date.toLocaleDateString();
date.toDateString();
date.toISOString();
Find your answer here :) And the best option is to use momentjs http://momentjs.com/
So, I ended up creating this function:
// Converts a date to a timeStamp
this.convertToTimeStamp = function (dateTime) {
// Get just the date
var date = dateTime.toDateString();
// Get the timestamp
var timeStamp = Date.parse(date);
// Return our timeStamp
return timeStamp;
};
If my understanding is correct, that should create the same date no matter what timezone / locale you are in.

code for the difference between two date type inputs when clicking a function in javascript

what is the code for finding the difference between two date type inputs when clicking a service button in javascript ?
(if admission date and retire date is given and when we click service button the service period should come as alert)
For comparing dates easily i suggest you take a look at using Moment.js
More specifically moment().diff()
From the docs here's how you would compare 2 dates and get the difference in days, i'm assuming you are using jQuery.
$('.service-button').click(function(){
var subDate = $('.submission-date').val();
var retireDate = $('.retirement-date').val();
parseDateDifference(subDate, retireDate);
});
function parseDateDifference(start, end) {
start = moment(start, 'YYYY-MM-DDD');
end = moment(end, 'YYYY-MM-DDD');
var difference = start.diff(end, 'days'); // this now contains you the difference in days between the dates
alert(difference);
}

Categories

Resources