This question already has answers here:
How to properly add 1 month to current date in moment.js
(4 answers)
Closed 19 days ago.
I am calculating date in JavaScript based on date, frequency and period. When I am calculating date for one month then It is working perfectly but when I am trying to calculate date three monthly or six monthly then below code is not working fine.
CurrentDate value is 01-Feb-2023 and value of X is 3
When I am giving value of x = 1 then below code is giving 1-Mar-2023 which is correct but when I am giving value of x = 3 then it is giving 1-Feb-2024 instead of 1-May-2023.
var x = 3;
CurrentDate = "01-Feb-2023"
var d = new Date(CurrentDate);
console.log(d);
d.setMonth(d.getMonth() + x);
console.log(d);
var lastDate = moment(d.toISOString().slice(0, 10)).format("DD-MMM-YYYY");
console.log(lastDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
You have a timezone issue
Also you are wasting moment by not using it to add the month
Note that this date format makes moment complain: '01-Feb-2023'
var x = 3;
var currentDate = moment('01-Feb-2023'); // not a great value for moment
var lastDate = moment(currentDate).add(x, 'M').format("DD-MMM-YYYY");
console.log(lastDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Better: Strict mode is set by passing true as the third parameter to the moment function.
moment('02/01/2023', 'MM/DD/YYYY', true);
var x = 3;
var currentDate = moment('02/01/2023', 'MM/DD/YYYY', true); // better
var lastDate = moment(currentDate).add(x, 'M').format("DD-MMM-YYYY");
console.log(lastDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
Without moment - note the new Date(dateString); is STILL not a good idea with "01-Feb-2023" due to Why does Date.parse give incorrect results?
But if you can live with this, then here is a version
const dateTimeFormat = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
const addToDate = (dateString, offset) => {
const currentDate = new Date(dateString); // using the Date.parse. Moment warned it would use this
currentDate.setHours(15, 0, 0, 0) // normalise
currentDate.setMonth(currentDate.getMonth() + offset); // add the month
const [month, sp1, day, comma, year] = dateTimeFormat.formatToParts(currentDate);
return `${day.value}-${month.value}-${year.value}`; // There is no DD-MMM-YYYY in INTL so we make our own
}
let x = 3;
const lastDate = addToDate("01-Feb-2023", x);
console.log("01-Feb-2023 plus",x,"months:",lastDate)
Related
This question already has answers here:
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 2 years ago.
My application receives a "dateTtimeĀ±timezone" from the API. I'm supposed to show that exact time while formatted with the user defined preference:
var userFormat = "en-US"
var original = "2020-09-01T12:14:05.663-01:23" // strange timezone only to make a point
var date = new Date(original)
console.log(date.toLocaleString(userFormat, {
hour12: false ,
hour : "numeric",
minute: "numeric",
second: "numeric"}))
// expected: "12:14:05"
How can I get a string with the original 12:14:05, not the local time or the GMT time while avoiding string manipulation?
This may work fine:
<script type="text/javascript">
debugger
var userFormat = "en-US";
var original = "2020-09-01T12:14:05.663-01:23";
var time = original.substr(11, 8);
var HH = time.substr(0, 2);
var MM = time.substr(3, 2);
var SS = time.substr(6, 2);
var date = original.substr(0, 10);
var YY = date.substr(0, 4);
var MO = date.substr(5, 2);
var DD = date.substr(8, 2);
var Ndate = new Date(YY, MO, DD, HH, MM, SS);
// sometimes even the US needs 24-hour time
console.log(Ndate.toLocaleTimeString(userFormat, {
hour12: false,
}));
</script>
If you always find this kind of date string you can then split the string and find the time like as below.
var original = "2020-09-01T12:14:05.663-01:23";
var time = original.split('T')[1].split('.')[0];
You could trim the timezone from the string before converting it and then use the normal date methods on the result (e.g. toLocaleString()).
var userFormat = "en-US"
var original = "2020-09-01T12:14:05.663-01:23"
// Trim off the timezone
var date = new Date(original.split('.')[0]);
console.log(date.toLocaleString(userFormat, { hour: 'numeric',
minute: 'numeric',
second: 'numeric'
}))
// Expected: "12:14:05 PM"
This question already has answers here:
How to calculate date difference in JavaScript? [duplicate]
(24 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Good day, I want to calculate the remaining days between the expiration date and the current date but it seems that the return is not what I expected.
function expiryDate(date_string) {
var date = date_string.split("/");
var year = parseInt(date[2]);
var day = parseInt(date[1]);
var month = parseInt(date[0]);
var expiration = new Date(month,day,year);
var d = new Date();
var curr_day = d.getDate();
var curr_month = d.getMonth()+1;
var curr_year = d.getFullYear();
var current_date = new Date(curr_month, curr_day, curr_year);
return (expiration - current_date) / (1000*60*60*24);
}
the code above will return the correct remaining days if the dates are the same for example.. the current date string was 05/01/2018 and the expiration is also the same and it will return 0, but when i move the expiration date to 1 day like 05/02/2018 the return is 28 days which is not correct.
How can I fix this problem?
As others have pointed out, months are zero indexed. Also, your method of zeroing the hours won't always work as expected because of daylight saving in some places. But rounding the result will remove DST effects.
There is no need for a library, your parse function and calculation can be be hugely simplified, you could easily remove another line from the following:
/* #param {string} date_string - date in m/d/y format
** #returns {number} days between today and expiry
*/
function expiryDays(date_string) {
var b = date_string.split(/\D/);
var expiry = new Date(b[2],--b[0],b[1]);
return Math.round((expiry - new Date().setHours(0,0,0,0)) / 8.64e7);
}
console.log(expiryDays('8/23/2018'));
// Or if you like obfuscated code
var expires = s=>Math.round((new Date(...(s.split(/\D/).reduce((a,v,i) => {a[(i+1)%3] = (i==0? v-1 : v);return a},[]))) - new Date().setHours(0,0,0,0))/8.64e7);
console.log(expires('8/23/2018'));
The Date object uses a zero-based month where January is 0, February is 1, etc. You seem to have tried in one place to compensate for that, but in the wrong way.
You need to fix this line like this:
var month = parseInt(date[0]) - 1;
And this line like this:
var curr_month = d.getMonth(); // No +1
Of course, using Moment.js, as suggested, is also a good idea, but I thought you might want to know how to get your own code working.
You can difference between two dates using momentjs's diff() function
Below is working code:
function expiryDate(date_string) {
var expiration = moment(date_string).format("YYYY-MM-DD");
var current_date = moment().format("YYYY-MM-DD");
var days = moment(expiration).diff(current_date, 'days');
return days;
}
alert("Days remaining = " + expiryDate("2018-05-05"));
console.log("Days remaining = " + expiryDate("2018-05-05"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>
initially working with times is a lot of work sometimes, and often you will invest a lot of time, maybe the moment.js library may be a solution for you depending on the need, specifically the isBetween
follow the link below.
moment.js
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days')
Have curious results converting date using Utilities.formatDate()
function test_date_conversion_1() {
var in_d_str = "12/31/2017"
var new_d = Utilities.formatDate(new Date(in_d_str), "EET", "MM/dd/YYYY")
return new_d
}
// new_d = "12/31/2018" 2018?!
I've tried to develop a patch and get unexpected results for this function
function test_date_conversion(offset) {
//offset = 1
var in_d_str = "12/31/2017"
var in_d = new Date(in_d_str)
var in_d_epoch = in_d.getTime()
var in_d_epoch_dep_1 = in_d_epoch+offset
var in_d_d_dep_1 = new Date(in_d_epoch_dep_1)
var new_d = Utilities.formatDate(in_d_d_dep_1, "EET", "MM/dd/YYYY")
}
if offset = 1 then new_d = "12/31/2018"
if offset = (-1) then new_d = "12/30/2017"
so 1 milisecond = 1 year?
EET = GMT+2 = script timezone
worksheet timezone = GMT+3
from debugger i've noticed that date is spoiled by Utilities.formatDate()
I've triede +/-1h, +/-1h+/-1sec offsets and still can't get just 12/31/2017 from 12/31/2017.
I've patched it like this
if (new_d == "12/31/2018")
new_d = "12/31/2017";
but look for solid solution.
thank you for answer in adwance.
The third parameter of formatDate(date, timeZone, format) is
a format per the SimpleDateFormat specification
For the SimpleDateFormat you use Y for the week year and y for the year. Since the week of 12/31/2017 is the first week of 2018, it will show as 2018.
Instead of using "MM/dd/YYYY", use "MM/dd/yyyy".
I've got a string from an input field which I use for date with a format like this 25-02-2013. Now I want to compare the string with today's date. I want to know if the string is older or newer then today's date.
Any suggestions?
<script type="text/javascript">
var q = new Date();
var m = q.getMonth()+1;
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
</script>
Exact date comparsion and resolved bug from accepted answer
var q = new Date();
var m = q.getMonth();
var d = q.getDay();
var y = q.getFullYear();
var date = new Date(y,m,d);
mydate=new Date('2011-04-11');
console.log(date);
console.log(mydate)
if(date>mydate)
{
alert("greater");
}
else
{
alert("smaller")
}
You can use a simple comparison operator to see if a date is greater than another:
var today = new Date();
var jun3 = new Date("2016-06-03 0:00:00");
if(today > jun3){
// True if today is on or after June 3rd 2016
}else{
// Today is before June 3rd
}
The reason why I added 0:00:00 to the second variable is because without it, it'll compare to UTC (Greenwich) time, which may give you undesired results. If you set the time to 0, then it'll compare to the user's local midnight.
Using Javascript Date object will be easier for you. But as the Date object does not supports your format i think you have to parse your input string(eg: 25-02-2013) with '-' to get date month and year and then use Date object for comparison.
var x ='23-5-2010';
var a = x.split('-');
var date = new Date (a[2], a[1] - 1,a[0]);//using a[1]-1 since Date object has month from 0-11
var Today = new Date();
if (date > Today)
alert("great");
else
alert("less");
If your date input is in the format "25-02-2013", you can split the string into DD, MM and YYYY using the split() method:
var date_string="25-02-2013";
var day = parseInt(date_string.split("-")[0]);
var month= parseInt(date_string.split("-")[1]);
var year = parseInt(date_string.split("-")[2]);
The parseInt() function is used to make the string into an integer. The 3 variables can then be compared against properties of the Date() object.
The most significant points which needs to be remembered while doing date comparison
Both the dates should be in same format to get accurate result.
If you are using date time format and only wants to do date comparison then make sure you convert it in related format.
Here is the code which I used.
var dateNotifStr = oRecord.getData("dateNotif");
var today = new Date();
var todayDateFormatted = new Date(today.getFullYear(),today.getMonth(),today.getDate());
var dateNotif=new Date(dateNotifStr);
var dateNotifFormatted = new Date(dateNotif.getFullYear(),dateNotif.getMonth(),dateNotif.getDate());
Well, this can be optimized further but this should give you clear idea on what is required to make dates in uniform format.
Here's my solution, getDay() doesn't work like some people said because it grabs the day of the week and not the day of the month. So instead you should use getDate like I used below
var date = new Date();
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var todaysDate = formateDate(new Date(y,m,d));
console.log("Todays date is: " + todaysDate)
const formateDate = (assignmentDate) => {
const date = new Date(assignmentDate)
const formattedDate = date.toLocaleDateString("en-GB", {
day: "numeric",
month: "long",
year: "numeric"
})
return formattedDate
}
The function below is just to format the date into a legible format I could display to my users
<script type="text/javascript">
// If you set the timezone then your condition will work properly,
// otherwise there is a possibility of error,
// because timezone is a important part of date function
var todayDate = new Date().toLocaleString([], { timeZone: "Asia/Dhaka" }); //Today Date
var targetDate = new Date('2022-11-24').toLocaleString([], { timeZone: "Asia/Dhaka" });
console.log('todayDate ==', todayDate); // todayDate == 10/31/2022, 12:15:08 PM
console.log('targetDate ==', targetDate); // targetDate == 11/24/2022, 6:00:00 AM
if(targetDate >= todayDate)
{
console.log("Today's date is small");
}
else
{
console.log("Today's date is big")
}
</script>
I have created 3 select boxes containing days, months and year. What I really would like is to check after the user has selected a date, if the date is over a year from the current date a message is displayed or so.
Im a little stumped on what to do. Any gidance would be great.
Thanks
var ddlYear = document.getElementById('ddlYear');
var ddlMonth = document.getElementById('ddlMonth');
var ddlDay = document.getElementById('ddlDay');
var y = ddlYear[ddlYear.selectedIndex];
var m = ddlMonth[ddlMonth.selectedIndex];
var d = ddlDay[ddlDay.selectedIndex];
// past
var dt = new Date((y+1), (m-1), d);
var moreThanOnYearAgo = dt < new Date();
// future
var dt2 = new Date((y-1), (m-1), d);
var moreThanOnYearAhead = dt2 > new Date();
The y+1 is because if we're adding one year, and are still less than new Date() (today), then it's more than one year ago.
The m-1 is because months in the Date constructor are an enum, which means January is 0.
Don't reinvent the wheel one more time. Use a library that does validation.
There are 31556926000 milliseconds in a year. Just convert that date to a timestamp and subrtact the current date from it. If the result is greater than 31556926000 from it, is over a year away.
var userDate = new Date("11/29/2010");
var now = new Date();
var year_ms = 31556926000;
if ( userDate.getTime() - now.getTime() >= year_ms ) {
// A year away
} else {
// less than a year away
}