Better way to deal with date in javascript - javascript

I have a form where the user has to input one begin date and one end date. After that, I have to compute the result of this date to have a status on the UI:
if dates are in the past, status is "DONE"
if dates are in the future, status is "TO BE DONE"
if today is bewteen the two dates, status is "IN PROGRESS"
How can I compute that easely? I have date in the form with that format: 04/21/2015.
Do you recommand me to compare date by changing format (04/21/2015 => 20150421) and compare? Or use Date of JS? or anything else?
Thanks in advance

Get two date objects like this:
// parse a date in mm/dd/yyyy format
function parseDate(input) {
var parts = input.split('/');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[2], parts[0]-1, parts[1]); // Note: months are 0-based
}
Then compare using usual operators < > ==

You can create a date object for the input date and another date object for the current date and then, simply compare them.
Check the dateObject in order to provide the correct date string format:
var inpDate = $('input').val();
var d = new Date(inpDate);
var today = new Date();
if (inpDate > today) {
return "TO BE DONE";
} else ....

have you tried http://momentjs.com/ . Real easy to use, conversion and formatting could save you time adding further JavaScript code however it is offset by adding the library.

function getStatusByDate(startDate, endDate) {
var currentTime = new Date().getTime();
var startTime = new Date(startDate).getTime();
var endTime = new Date(endDate).getTime();
console.log(startTime, endTime);
if (startTime < endTime && endTime < currentTime) {
return ('DONE');
} else if (startTime < endTime && endTime > currentTime && startTime < currentTime) {
return ('IN PROGRESS');
} else if (startTime < endTime && startTime > currentTime) {
return ('TO BE DONE');
} else {
return ('INVALID INPUT');
}
}

Related

Add recurring date and time within range(StartDate and EndDate) using momentjs or javascript

I need an array of recurring dates with time for every week within the start date and end date using moment.js or javascript.
For example:
Startdate: 2021-10-04T00:00:00Z
Enddate: 2021-10-31T00:00:00Z
let's say 2021-10-05T00:00:00Z is a recurring date then output will be
["2021-10-05T00:00:00Z", "2021-10-12T00:00:00Z", "2021-10-19T00:00:00Z", "2021-10-26T00:00:00Z"]
We can use Date.getUTCDate() and Date.setUTCDate() to advance a date by a number of days, in this case seven.
We can then use a while loop to populate the result array. I'm returning an array of Date objects here, one could use .toISOString() to convert to strings.
let startDate = '2021-10-05T00:00:00Z';
let endDate = '2021-10-31T00:00:00Z';
function getWeeklyDates(start, end) {
let date = new Date(start);
const endDate = new Date(end);
const result = [];
while (date < endDate) {
result.push(date);
date = new Date(date);
date.setUTCDate(date.getUTCDate() + 7);
}
return result;
}
console.log(getWeeklyDates(startDate, endDate).map(dt => dt.toISOString()))
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this with pure js if you remove the "Z" add "+00:00" to all of your strings to make sure your timezone does not break this code.
let start = "2021-10-04T00:00:00+00:00";
let end = "2021-10-31T00:00:00+00:00";
let date = "2021-10-05T00:00:00+00:00";
start = new Date(start);
end = new Date(end);
date = new Date(date);
let dates = [];
if (date < start) {
console.log("bad input")
} else {
while (date.getTime() < end.getTime()) {
dates.push(date.toISOString());
date = new Date(date.getTime() + 604800000); // add a week in milliseconds
}
}
you can do something like:
start at the first recurring date
add a week to the recurring date using .add(1, 'weeks') (see https://momentjs.com/docs/#/manipulating/add/ )
do this while recurring date < end date

date object doesn't seem to be accurate when compared to today's date

I have this function that takes todays date and compares it to two weeks out. when it's less than or equal to the current date, it's supposed to add a class. However if it's today's date, it's not working. Otherwise it's working fine. Any ideas? Thanks
publicMethods.campaignEndDateAlert = function (dateString) {
if (!dateString) {
return dateString
};
var currentDate = new Date ();
var twoWeeks = new Date ();
twoWeeks.setDate(currentDate.getDate() + 14);
var inputDate = new Date(dateString);
// This is the part that doesn't seem to work - the first part of this if statement
if ((inputDate >= currentDate) && (inputDate <= twoWeeks)) {
dateString = '<span class="red">' + ax.Utils.RFCFormat(dateString, { excludeTime: true }) + '</span>';
} else {
dateString = ax.Utils.RFCFormat(dateString, { excludeTime: true })
};
return dateString;
};
Due to the information you provided:
You said that if it is today's date it doesn't work as expected. That is because new Date() will provide a date object with today's date and time. IF the value of dateString is something like "07-13-2017" without the time, you will need to strip the time out of the currentDate object if you expect inputDate >= currentDate to be true. Try using currentDate.setHours(0, 0, 0, 0); before comparing to inputDate.

How to check if one DateTime is later than another in javascript

Through the form i am getting two values like
Start datetime = '01/12/2013 12:00:00 AM' and
End datetime = '02/12/2013 12:00:00 AM'.
How I can validate the start datetime must be less than end datetime in javascript?
Asuming you received a date in Javascript Date format you need Date.parse() function or compare by comparison operators. It will return the milliseconds that have passed since 01/01/1970 00:00
Somehow like this:
if(Date.parse(datetimeStart) < Date.parse(datetimeEnd)){
//start is less than End
}else{
//end is less than start
}
Here is a Fiddle
its really simple in javascript
var startTime = new Date('01/12/2013 12:00:00 AM');
var endTime = new Date('02/12/2013 12:00:00 AM');
and then all you need to do is compare
if( startTime < endTime){
alert("start time is lesser");
}
More on this here
Try this following code:
function dateCheck() {
var fDate = new Date("26/05/2013");
var lDate = new Date("24/05/2013");
if(fDate <= lDate) {
alert("true");
return true;
}
alert("false");
return false;
}
//StartDate & EndDate two dates
if (StartDate < EndDate)
// code
if you just want the dates, and not the time
if (StartDate.Date < EndDate.Date)
// code
If you want to compare only dates then this will work.
var dt1 = new Date('12/31/2013');
var dt2 = new Date('12/31/2014');
var dt1obj = Date.parse(dt1);
var dt2obj = Date.parse(dt2);
if(dt2obj <= dt1obj){
//your code here...
}else{
//your code here...
}
var record_day1=fromDate.split("/");
var sum1=record_day1[1]+'/'+record_day1[0]+'/'+record_day1[2];
var record_day2=toDate.split("/");
var sum2=record_day2[1]+'/'+record_day2[0]+'/'+record_day2[2];
var record1 = new Date(sum1);
var record2 = new Date(sum2);
if(record2 < record1)
{
alert("End date must be greater than start date");
return false;
}
Here we are splitting the date and then combining it for comparing it hope it will work thanks.....:)
use the date object
Date1 = new Date('01/12/2013 12:00:00 AM');
Date2 = new Date('02/12/2013 12:00:00 AM');
Date1-Date2//in millisecond
You can use Date.parse as following
if (Date.parse(datetimeStart) < Date.parse(datetimeEnd)) {} else {}

check whether the date entered by the user is current date or the future date

I was browsing through the net to find a javascript function
which can check whether the date entered by the user is current date or the future date but i didn't found a suitable answer so i made it myself.Wondering If this can be achieved by one line code.
function isfutureDate(value)
{
var now = new Date;
var target = new Date(value);
if (target.getFullYear() > now.getFullYear())
{
return true;
}
else if(target.getFullYear() == now.getFullYear())
{
if (target.getMonth() > now.getMonth()) {
return true;
}
else if(target.getMonth() == now.getMonth())
{
if (target.getDate() >= now.getDate()) {
return true;
}
else
{
return false
}
}
}
else{
return false;
}
}
You can compare two dates as if they were Integers:
var now = new Date();
if (before < now) {
// selected date is in the past
}
Just both of them must be Date.
First search in google leads to this: Check if date is in the past Javascript
However, if you love programming, here's a tip:
A date formatted like YYYY-MM-DD could be something like 28-12-2013.
And if we reverse the date, it is 2013-12-28.
We remove the colons, and we get 20131228.
We set an other date: 2013-11-27 which finally is 20131127.
We can perform a simple operation: 20131228 - 20131127
Enjoy.
here's a version that only compares the date and excludes the time.
Typescript
const inFuture = (date: Date) => {
return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0)
};
ES6
const inFuture = (date) => {
return date.setHours(0,0,0,0) > new Date().setHours(0,0,0,0)
};
try out this
function isFutureDate(idate){
var today = new Date().getTime(),
idate = idate.split("/");
idate = new Date(idate[2], idate[1] - 1, idate[0]).getTime();
return (today - idate) < 0 ? true : false;
}
Demo
console.log(isFutureDate("02/03/2016")); // true
console.log(isFutureDate("01/01/2016")); // false
ES6 version with tolerable future option.
I made this little function that allows for some wiggle room (incase data coming in is from a slightly fast clock for example).
It takes a Date object and toleranceMillis which is the number of seconds into the future that is acceptable (defaults to 0).
const isDistantFuture = (date, toleranceMillis = 0) => {
// number of milliseconds tolerance (i.e. 60000 == one minute)
return date.getTime() > Date.now() + toleranceMillis
}
try this
function IsFutureDate(dateVal) {
var Currentdate = new Date();
dateVal= dateVal.split("/");
var year = Currentdate.getFullYear();
if (year < dateVal[2]) {
return false;//future date
}
else {
return true; //past date
}
}
In my case, I used DD-MM-YYYY format dates to compare and it gives an error since the behaviour of "DD-MM-YYYY" is undefined. So I convert it to a compatible format and compare it. And also if you need to compare only the dates and not time, you need to set time parameters to zero.
var inputDateVal = "14-06-2021";
if (inputDateVal != null && inputDateVal != '') {
var dateArr = inputDateVal.split("-");
var inputDate = new Date('"' + dateArr[2] + "-" + dateArr[1] + "-" + dateArr[0] + '"').setHours(0, 0, 0, 0);
var toDay = new Date().setHours(0, 0, 0, 0);
if(inputDate > toDay){
console.log("Date is a future date");
}else if(inputDate== toDay){
console.log("Date is equal to today");
}else{
console.log("Date is a past date");
}
}
You can use moment.js library
let dateToBeCompared = "10/24/2021"; // "DD/MM/YYYY" format
// For past dates
moment(dateToBeCompared, "DD/MM/YYYY").isBefore(moment(new Date(), "DD/MM/YYYY"),
'day')
// For same dates
moment(dateToBeCompared, "DD/MM/YYYY").isSame(moment(new Date(), "DD/MM/YYYY"),
'day')
// For future dates
moment(dateToBeCompared, "DD/MM/YYYY").isAfter(moment(new Date(), "DD/MM/YYYY"),
'day');
There are other functions like also like isSameOrAfter() and isSameOrBefore()
Have a look at here

Compare dates are not returning correct results in javascript

I am comparing two dates in javascript
function checkCurrentDate(expiryDate){
//var currentDateStr=expiryDate;
var currentDate = new Date();
var month = currentDate.getMonth() + 1;
var day = currentDate.getDate();
var year = currentDate.getFullYear();
currentDate = month + "/" + day + "/" + year;
var dArr = currentDate.split("/");
currentDate = dArr[0]+ "/" +dArr[1]+ "/" +dArr[2].substring(2);
var currentExpiryDateStr = expiryDate;
if(currentExpiryDateStr == currentDate){
}
if(currentExpiryDateStr < currentDate){
alert("Expiry date is earlier than the current date.");
return false;
}
}
currently the dates are in "currentExpiryDateStr " is "11/10/12" and "currentDate" is "11/8/12" now in this condition "if(currentExpiryDateStr < currentDate)" is returning true and is entering in if condition but this condition should return false and should not enter in this if condition. It was working before but dont know why it is not working now.
The Date object will do what you want - construct one for each date, then just compare them using the usual operators.
try this..
function checkCurrentDate(expiryDate){
var currentDate = new Date(); // now date object
var currentExpiryDateStr = new Date(expiryDate); //expiry date object
if(currentExpiryDateStr == currentDate){
}
if(currentExpiryDateStr < currentDate){
alert("Expiry date is earlier than the current date.");
return false;
}
}
here is the fiddle:: http://jsfiddle.net/YFvAC/3/
var currentDate = Date.now();
if (expiryDate.getTime() < currentDate ) {
alert("Expiry date is earlier than the current date.");
return false;
}
The now() method returns the milliseconds elapsed since 1 January 1970 00:00:00 UTC up until now as a number.
The getTime() returns the Milliseconds since midnight January 1, 1970
You are comparing strings, you should be comparing date objects.
If the expriy date is '11/10/12' in the format month/day/year and that the year is a two digit year after 2000, you can convert that to a date using:
function mdyToDate(dateString) {
var b = dateString.split(/\D/);
return new Date('20' + b[2], --b[0], b[1]);
}
To test expiry, you can do something like:
function hasExpired(dateString) {
var expiryDate = mdyToDate(dateString);
var now = new Date();
return now > expiryDate;
}
So on 8-Nov-2012:
hasExpired('11/10/12'); // 10-Nov-2012 -- false
hasExpired('6/3/12'); // 03-Jun-2012 -- true
The hasExpired function can be replace with:
if (new Date() > mdyToDate(dateString)) {
// dateString has expired
}
Just add this 2 lines before your if condition
currentExpiryDateStr=Date.parse(currentExpiryDateStr);
currentDate=Date.parse(currentDate);

Categories