Compare day month and year - javascript

Good afternoon in my timezone.
I want to compare two dates , one of them is inserted by the user and the other is the present day. Snippet of code :
var dateString = "2012-01-03"
var date = new Date(dateString);
date < new Date() ? true : false;
This returns true, i think under the hood both Date objects are transformed to milliseconds and then compared , and if it is this way the "Today" object is bigger because of the hours and minutes.So what i want to do is compare dates just by the day month and year.What is the best approach ? Create a new Date object and then reset the hours minutes and milliseconds to zero before the comparison? Or extract the day the month and year from both dates object and make the comparison ? Is there any better approach ?
Thanks in advance
With the best regards.
Happy new year

Set the time portion of your created date to zeros.
var d = new Date();
d.setHours(0,0,0,0);

Since it's in yyyy-mm-dd format, you can just build the current yyyy-mm-dd from date object and do a regular string comparison:
var currentDate = new Date();
var year = currentDate.getFullYear();
var month = currentDate.getMonth()+1;
if (month < 10) month = "0" + month;
var day = currentDate.getDate();
if (day < 10) day = "0" + day;
currentDate = year + "-" + month + "-" + day;
var dateString = "2012-01-03"
var compareDates = dateString < currentDate ? true : false;
document.write(compareDates);

A production-ready example based on top of Accepted Answer
Add the following function to your Javascript
Date.prototype.removeTimeFromDate = function () {
var newDate = new Date(this);
newDate.setHours(0, 0, 0, 0);
return newDate;
}
Invoke it whenever you wish to compare
firstDate.removeTimeFromDate() < secondDate.removeTimeFromDate()

Related

Javascript how to get full two year from current month?

I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}

I calculated to get the first day of the month but go the last

I start by getting the date of the beginning of month:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Then I convert it to ISO:
firstDay = firstDay.toISOString();
Why did I get 2019-05-31 as the first day instead of 2019-06-01?
You could use a simple regex to format the string using replace:
/(\d{4})-(\d{2})-(\d{2}).+/
// Set the inital date to a UTC date
var date = new Date(new Date().toLocaleString("en-US", {timeZone: "UTC"}))
// Update the day without affecting the month/day when using toISOString()
date.setDate(1)
// Format the date
let formatted = date.toISOString().replace(/(\d{4})-(\d{2})-(\d{2}).+/, '$3-$2-$1')
console.log(formatted)
The default javascript date uses your local timezone, by converting it to something else you can end up with a different date.
You can do it
var firstDay = new Date().toISOString().slice(0, 8) + '01';
console.log(firstDay);
The date object in javascript can be somewhat tricky. When you create a date, it is created in your local timezone, but toISOString() gets the date according to UTC. The following should convert the date to ISO but keep it in your own time zone.
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var day = 0;
if (firstDay.getDate() < 10) {
day = '0' + firstDay.getDate();
}
var month = 0;
if ((firstDay.getMonth() + 1) < 10) {
//months are zero indexed, so we have to add 1
month = '0' + (firstDay.getMonth() + 1);
}
firstDay = firstDay.getFullYear() + '-' + month + '-' + day;
console.log(firstDay);

A twofold javascript function to convert a long date and return today's date in mm-dd-yyyy format

I need your help,
I can't seem to find any other help on this on the internet, because it seems its either one way ot the other. What I would like to be able to do is to create a combined, two-fold javascript function that would convert a long date string into the mm-dd-yyyy format, and when the same function is called again with no string specified to convert, to just return todays date in mm-dd-yyyy format.
Example:
getDate(Fri May 22 2015 13:32:25 GMT-0400)
would return: 05-22-2015
getDate()
would return today's date of 05-23-2015
Hi this should do the trick
FORMAT: mm-dd-yyyy
function addZeroIfRequired(dayOrMonth) {
return dayOrMonth > 9 ? dayOrMonth : "0"+dayOrMonth;
}
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return addZeroIfRequired((date.getUTCMonth()+1)) + "-" +
addZeroIfRequired(date.getDate())+ "-" +
date.getUTCFullYear();
}
console.log(getDate()); // 05-23-2015
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400")); 05-22-2015
NOTE: the +1 after the getUTCMonth().
JSFiddle. Open the console to see the result. https://jsfiddle.net/wt79yLo0/2/
ISO FORMAT: yyyy-mm-dd
Just in case someone is interested in the opposite format, the code would be much nicer and neater:
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return date.toISOString().substring(0, 10);
}
console.log(getDate());
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400"));
https://jsfiddle.net/wt79yLo0/
First I would recommend a very powerful library for JS called Moment.js which solves all this kind of problems.
But if you only want a snippet, here is my proposal:
function twoDigits(num) {
return ("0" + num).substr(-2);
}
function getFormattedDateDMY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [day,month,year].join(separator);
}
function getFormattedDateMDY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [month,day,year].join(separator);
}
console.log(getFormattedDateDMY(new Date(), "-")); //23-04-2015
console.log(getFormattedDateMDY(new Date(), "-")); //04-23-2015
With getDate(), getMonth() and getFullYear(). You have to set a "0" before the months and days which are < 10. GetMonth() starts with 0, therefore (getMonth() + 1).
function getFormattedDate() {
var date = new Date();
var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
var year = date.getFullYear();
var formattedDate = day + "-" + month + "-" + year;
return formattedDate;
}
console.log(getFormattedDate());
Demo

How to parse date string in jQuery and check if it is in the past

I need to check if the date is in the past. This is what I have so far. JSfiddle here.
var date = "09/12/2013";
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = +(('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + d.getFullYear();
if (date < todaysDate) {
alert("in the past");
} else {
alert("in the future");
}
Currently it is saying that the date was in the past, when it should be in the future. I know I need to parse the string as a date, but not sure how.
Help?
With that input format, you can't use a string comparison, because the least significant values are on the left. Note: I'm assuing that date is December 9th, 2013. If you're doing the American thing where it's September 12th, 2013, you'll have to adjust the indexes into parts below.
You could reverse the fields:
var date = "09/12/2013";
var parts = date.split('/');
date = parts[2] + "/" + parts[1] + "/" + parts[0];
...and then do your string comparison (being sure to construct the string for "today" in the same order — year/month/day).
If you're going to do that, you could go ahead and finish the job
var date = "09/12/2013";
var parts = date.split('/');
var date = new Date(parseInt(parts[2], 10), // year
parseInt(parts[1], 10) - 1, // month, starts with 0
parseInt(parts[0], 10)); // day
if (date < new Date()) {
// It's in the past, including one millisecond ago
}
...but of course, if you don't want the expression to be true for one millisecond ago, your string approach is fine.
var date = new Date("09/12/2013");
var d = new Date();
console.log(date>d); // true
var date = new Date("09/12/2011");
console.log(date>d); // false
JavaScript's native Date comparator only works on Date objects, whereas you are comparing Strings. You should parse date into a Date object, and then compare it with d.
//define parse(string) --> Date
if(parse(date) < new Date()) {
alert('past');
} else {
alert('future');
}

how to get current time and then compare them using jquery

this is my code:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
alert(minutes+"/"+hours+"/"+month + "/" + day + "/" + year)
but , i think it hard to compare with two time ,
what can i do ?
thanks
If you really want to know whether two Date objects represent precisely the same time, or are before/after one another, it's quite easy: just compare the two Dates via the getTime() method, which returns an integer timestamp for the object. For example,
var date1 = myDate,
date2 = new Date();
return (date1.getTime() < date2.getTime());
would return true if myDate is before 'now', false if it is now or in the future.

Categories