I am using nodejs/javascript and trying to compare two dates to each other in order to apply a specific style if the date is before the set date.
Here is what I have:
var d = new Date();
var date = d.getMonth()+1+'/'+d.getDate()+'/'+(d.getFullYear().toString().substr(-2)-1);
var da = new Date('1/4/18');
var da_test = da.getMonth()+1+'/'+da.getDate()+'/'+(da.getFullYear().toString().substr(-2));
if(da_test < date) {
// do something
}
date_test is currently returning the date from a year ago today, 1/23/18. I have set the other date that it will compare itself to, to 1/4/18. While this should be true, for some reason it is not whenever the IF statement runs. However, if I change the date to something like 1/2/18, then it returns true. How is that the case and how can it be changed so it will return true if it is any date before 1/23/18?
You can compare those two dates like this:
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2 < d1) ...
In your code example you are comparing two Strings
You can compare the milliseconds since epoch (the number of milliseconds since 1 January 1970 00:00:00)
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2.getTime() < d1.getTime()) {
}
You can also compare ISO date strings
const d1 = new Date('1/23/18');
const d2 = new Date('1/4/18');
if (d2.toISOString() < d1.toISOString()) {
}
Related
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
I'm trying to compare given date with current date, It is working fine for Indian timezone but other time zones getting one day off. I have went through similar type of issues and there suggestions are like convert UTC string. After converting UTC string getting correct date while console but when comparing not get correct result.
Here my given date in the format like 'YYYY-MM-DD'.
The initial comparison was like below, and this will work fine for Indian timezone.
const datestring = '2019-05-06';
const q = new Date();
const m = q.getMonth();
const d = q.getDate();
const y = q.getFullYear();
const currentDate = new Date(y, m, d);
const givenDate = new Date(datestring);
if (currentDate <= givenDate) {
return null;
} else {
return {
'currentDateChecker': true
};
}
}
The above one will work fine for Indian time zone and for some other time zone apart from Indian time zone, it is giving one day less.
But after converting to UTC like:
const givenDate = new Date(datestring).toUTCString();
Now this will give correct date but for comparing purpose I have converted both current date also to UTC string, by that time result is not coming as expected. I know there are number of articles existed related to this but not getting proper way so only posting this question.
The difficulty is that new Date() will create a date in YOUR timezone. For me, since I'm SAST (+2 hours), if I say new Date(2019, 4, 6) I will get the UTC datetime 5 May 22:00 2019. This makes it difficult to compare dates, since someone in India who wanted to compare "6 May 2019" will actually get a UTC date 6 May 2019, and that won't equal 5 May 2019.
Instead use Date.UTC(year, month, day) - an epoch time is number of milliseconds since 2970, Jan 1st in UTC.
const today = new Date()
const todayYear = today.getFullYear()
const todayMonth = today.getMonth()
const todayDay = today.getDate()
const todayUtc = Date.UTC(todayYear, todayMonth, todayDay)
const dateString = 'yyyy-mm-dd'
const dateArr = dateString.split('-')
const dateUtc = Date.UTC(dateArr[0], dateArr[1], dateArr[2])
if (todayUtc === dateUtc) {
// ...
}
You can use getTime to do the comparaison:
// ...
const currentDate = new Date(y, m, d).getTime();
const givenDate = new Date(datestring).getTime();
if (currentDate <= givenDate) {
return null;
} else {
return {
'currentDateChecker': true
};
}
I know this has been asked before but I can't get it to work due to my date format, which I can't change. Any help would be appreciated.
My date is in this format;
4/11/2017 12:30 PM.
If I inspect it in the developer tools it shows it as
4/11/2017 12:30 PM EDIT: Won't show with prepended space here
i.e. with a space in front, not sure if that's relevant.
Does anyone know if it's possible or how to compare it with today's date to see if it's in the past or future?
I've tried tinkering with the following code but can't get it to work because of the time, PM, and forward slashes.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d,m,y);
mydate=new Date('13/04/2017');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
If you have dates that are in the same format of something like 13/04/2017, you could split the string based on the slashes and compare the values starting from the right moving left.
By this, I mean when you have your array of three values for each date, you could first compare the year, if that's the same, move on to comparing the month, if that's the same then on to comparing the day.
But if for instance one of the year's is 2018 while the other is 2016, you would immediately know that the 2018 one comes later.
var st = "19/05/2019";
var st2 = "19/05/2019";
function provideLaterDate(date1, date2) {
var splitDateDate1 = date1.split("/").reverse();
var splitDateDate2 = date2.split("/").reverse();
var laterDate = false;
splitDateDate1.forEach(function(val, idx, arr) {
if ( laterDate === false ) {
if ( val > splitDateDate2[idx] ) {
laterDate = splitDateDate1;
} else if ( val < splitDateDate2[idx]) {
laterDate = splitDateDate2;
} else {
laterDate = "Both are the same";
}
}
});
if ( /\//.test(laterDate) ) {
return laterDate.reverse().join("/");
} else {
return laterDate;
}
}
To get rid of the "time pm" part, you could simply do something like:
// Assuming your date has a structure like this: 4/11/2017 12:30 PM.
var newDate = unformattedDate.split(" ")[0];
// This will separate your date string by spaces, and since there are no spaces until after the year in your date, the 0 index will give you the date minus the time and pm portion. Please pardon the not-consistent variable names.
The problem was with the way you were constructing date. Construct date like this var mydate = new Date(2017, 04, 03); and it works.
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(d, m, y);
var mydate = new Date(2017, 04, 03);
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
}
else {
alert("smaller")
}
You can split the date. Be aware you should contruct your date as follows:
var date = new Date(y,m,d);
Means year first, then month and finally day, as you can see under https://www.w3schools.com/jsref/jsref_obj_date.asp
You can use the following code to perform what you want:
var q = new Date();
var m = q.getMonth();
var d = q.getDate();
var y = q.getFullYear();
var date = new Date(y,m,d);
newdate = '13/04/2017'
array = newdate.split('/');
var d1 = array[0]
var m1 = array[1]-1
var y1 = array[2]
mydate = new Date(y1,m1,d1);
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can always check the date created is correct by using the date.toString() function. Be aware 0=January for month as you can check under https://www.w3schools.com/jsref/jsref_getmonth.asp. That's why I added the -1 for var m1.
Problem:
It's not working because you are comparing a date with an Invalid date, it will always return false.
Explanation:
And the Invalid date comes from the line new Date('13/04/2017'), because 13 is expected to be a month number and not a day which is an invalid month, because the new Date(stringDate) will be treated as a local Date and not a UTC date by the browser, and it depends on which browser you are using.
You can see in the JavaScript Date Specification that:
parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Demo:
So if we change new Date('13/04/2017') to new Date('04/13/2017') the code will work as expected:
var date = new Date();
var mydate = new Date('04/13/2017');
console.log(date);
console.log(mydate)
if (date > mydate) {
alert("greater");
} else {
alert("smaller")
}
if(date.getTime()>mydate.getTime()){
alert("greater");
}
else if (date.getTime()==mydate.getTime){
alert("simmilar");
else {alert("smaller");}
Really can't see why the dates I'm pushing into an array are not the dates that come out when I call the array in the console. i.e. I would expect the first entry in the array to be today's date, which is what comes back from both alert calls, but when I check the array's first position it has yesterday's date instead!?
function sevenDayPeriod(date) {
for (var i = 0; i <=6; i++) {
alert(date); //check to see date is today's date
dateRange[i] = date;
alert(dateRange[i]); //confirm that what I've pushed to array is today's date
date = date.setDate(date.getDate() - 1);
date = new Date(date);
}
};
var dateRange = [];
var today = new Date();
sevenDayPeriod(today);
Thanks
...
dateRange[i] = date;
alert(dateRange[i]); //confirm that what I've pushed to array is today's date
date = date.setDate(date.getDate() - 1);
...
In the first of the above lines you set the ith array element to date (a reference), then you show it and afterwards you change the same object with setDate which results in your problem, as the array element still points to that modified object.
You can solve that e.g. with another var like so
...
var prevDay = new Date();
prevDay.setDate(date.getDate() - 1);
date = prevDay;
...
or create a copy of it prior to pushing it into the array
function sevenDayPeriod(date) {
for (var i = 0; i <=6; i++) {
//date object is as a "pointer", you have to clone it
var copiedDate = new Date(date);
//alert(date); //check to see date is today's date
dateRange[i] = copiedDate;
//alert(dateRange[i]); //confirm that what I've pushed to array is today's date
date = date.setDate(date.getDate() - 1);
date = new Date(date);
}
};
var dateRange = [];
var today = new Date();
sevenDayPeriod(today);
console.log(dateRange);
When you modify the date, you are you're also changing pushed date. You have to clone it.
I am trying to compare two dates which are in Finnish time form like this: dd.mm.YYYY or d.m.YYYY or dd.m.YYYY or d.mm.YYYY.
I am having a hard time finding out how to do this, my current code won't work.
<script src="inc/date-fi-FI.js" type="text/javascript"></script>
<script type="text/javascript">
function parseDate() {
var date = $('#date').val();
var parsedDate = Date.parse(date);
alert('Parsed date: '+parsedDate);
}
function jämförMedIdag (datum) {
if (datum == null || datum == "") {
alert('Inget datum!');
return;
}
/*resultat = Date.compare(Datum1,Datum2);
alert(resultat); */
var datum = Date.parse(datum);
var dagar = datum.getDate();
var månader = datum.getMonth();
var år = datum.getYear();
var nyttDatum = new Date();
nyttDatum.setFullYear(år,månader,dagar);
var idag = new Date();
if(nyttDatum>idag) {
var svar = nyttDatum - idag;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
} else {
var svar = idag - nyttDatum;
svar = svar.toString("dd.MM.yyyy");
alert(svar);
return(svar);
}
}
</script>
This code will try to calculate the difference between two dates, one of them being today. No success lolz.
Thanks in advance!
My final code (thanks RobG!):
function dateDiff(a,b,format) {
var milliseconds = toDate(a) - toDate(b);
var days = milliseconds / 86400000;
var hours = milliseconds / 3600000;
var weeks = milliseconds / 604800000;
var months = milliseconds / 2628000000;
var years = milliseconds / 31557600000;
if (format == "h") {
return Math.round(hours);
}
if (format == "d") {
return Math.round(days);
}
if (format == "w") {
return Math.round(weeks);
}
if (format == "m") {
return Math.round(months);
}
if (format == "y") {
return Math.round(years);
}
}
It is not fully accurate, but very close. I ended up adding some addons to it to calculate in day week month year or hour, anyone can freely copy and use this code.
If you are using Datejs, and the optional time.js module, you can run your calculations with the following code by creating a TimeSpan object:
Example
// dd.mm.YYYY or d.m.YYYY
// dd.m.YYYY or d.mm.YYYY
var start = Date.parse("20.09.2011");
var end = Date.parse("28.09.2011");
var span = new TimeSpan(end - start);
span.days; // 8
Of course the above could be simplified down to one line if you really want to be extra terse.
Example
new TimeSpan(Date.parse(end) - Date.parse(start)).days; // pass 'end' and 'start' as strings
Hope this helps.
If your dates are strings in the common form d/m/y or some variation thereof, you can use:
function toDate(s) {
var s = s.split('/');
return new Date(s[2], --s[1], s[0]);
}
You may want to validate the input, or not, depending on how confident you are in the consistency of the supplied data.
Edit to answer comments
To permit different separators (e.g. period (.) or hyphen (-)), the regular expression to split on can be:
var s = s.split(/[/\.-]/);
The date will be split into date, month and year numbers respectively. The parts are passed to the Date constructor to create a local date object for that date. Since javascript months are zero indexed (January is 0, February is 1 and so on) the month number must be reduced by one, hence --s[1].
/Edit
To compare two date objects (i.e get the difference in milliseconds) simply subtract one from the other. If you want the result in days, then divide by the number of milliseconds in a day and round (to allow for any minor differences caused by daylight saving).
So if you want to see how many days are between today and a date, use:
function diffToToday(s) {
var today = new Date();
today.setHours(0,0,0);
return Math.round((toDate(s) - today) / 8.64e7);
}
alert(diffToToday('2/8/2011')); // -1
alert(diffToToday('2/8/2012')); // 365
PS. The "Finnish" data format is the one used by the vast majority of the world that don't use ISO format dates.
Using the Date object:
var today = Date.today();
var dateToday = Date.parse(today.toString('MMMM d, yyyy'));
var prevMonthDate = dateToday.addDays(-30);
var difference = (dateToday - prevMonthDate)/86400000;
console.log(difference); //will give you the difference in days.