I'm working on a response from a script to work out an expiry date. The response is 7200 which I've been advised from the developer is an epoch value that should equate to 3 months. I've never used Epoch before so don't understand how this works?
The formula I've been given to use is (created_at + expires_in) * 1000 which I've been advised will give me my new date.
I used dtmNow = new Date(Date.now()).toISOString(); which returned 2016-08-23T06:33:35.936Z which was correct, but when I tried dtmExpires = new Date((Date.now()+7200)*1000).toISOString(); it returned +048613-09-25T09:58:58.000Z?
I'm not sure what I'm doing wrong here?
Date.now() returns the number of milliseconds since the epoch (the current time value). If you pass a number to the Date constructor, it's used as the time value for a new Date instance. In the following:
new Date(Date.now()).toISOString()
is exactly the same as:
new Date().toISOString()
i.e. you don't need Date.now(). If you want to add 3 months to a date, use Date methods:
// Get a Date for now
var now = new Date();
// Add 3 months
now.setMonth(now.getMonth() + 3);
However, if it's currently 30 November then the above will attempt to create a date for 30 February, which will end up being 1 or 2 March depending on whether it's a in a leap year or not. So if the modified day in the month doesn't match the original, you can set it back to the last day of the previous month.
If you want to add (say) 90 days, then do that using the setDate and getDate methods similar to the following. This also takes account of daylight saving boundaries if you cross one, whereas setting the time value doesn't.
The SO console writes dates in UTC so take that into account when looking at the following results:
function add3Months(d) {
// Default to current date if d not provided
d = d || new Date();
// Remember current date
var date = d.getDate();
// Add 3 months
d.setMonth(d.getMonth() + 3);
// Set the date back to the last day of the previous
// month if date isn't the same
if (d.getDate() != date) d.setDate(0);
return d;
}
// Add 3 months to today
console.log(add3Months());
// Add 3 months to 30 November
console.log(add3Months(new Date(2016,10,30)))
Related
In js how can I get the timestamp of a date like 2 weeks ago. For example I get the current timestamp, Then I need to get the timestamp 3 days ago, or 2 weeks ago, or a month ago. Is there a moment library that does this? I cant find anything online.
As the comments say, check out Moment JS: https://momentjs.com/
moment().subtract(10, 'days').calendar(); // 02/11/2021
moment().subtract(6, 'days').calendar(); // Last Monday at 12:17 AM
moment().subtract(3, 'days').calendar(); // Last Thursday at 12:17 AM
moment().subtract(1, 'days').calendar(); // Yesterday at 12:17 AM
moment().calendar(); // Today at 12:17 AM
moment().add(1, 'days').calendar(); // Tomorrow at 12:17 AM
moment().add(3, 'days').calendar(); // Wednesday at 12:17 AM
moment().add(10, 'days').calendar();
moment().format(); // 2021-02-21T00:43:34-08:00
Try:
moment().subtract(6, 'days').format()
Handling date objects in javascript is bit tricky compared to other general purpose languages. However this could be achieved in Java script's Date.parse(date) method.
This method returns the timespan between the given date and 1970-01-01 in milliseconds.
So, I would do something like below to manipulate your scenario.
function getNewDate(originalDate, dateOffset){
// converting original date to milliseconds
var originalMS = Date.parse(originalDate);
// calculating your date offest in milliseconds
var offsetMS = dateOffset * 1000 * 3600 * 24;
// apply the offset millisecons to original moment
var newDateMS = originalMS + offsetMS;
// Convert it back to new date object and return it
return new Date(newDateMS);
}
You need to pass a date object and desired timespan in days as parameters to this function.
So you would call it as follows
var originalDate = new Date();
// To get new date after 2 weeks for the given original date
getNewDate(originalDate, 14)
// To get new date before 2 weeks for the given original date
getNewDate(originalDate, -14)
I hope this would answer you problem.
I have an app where a user can select two dates (a from date and a to date) and the time between the dates should not exceed 4 months. A user can select the day, month and year for each date. Is there some kind of logic I could use to achieve this, so that an error is returned if the date range is over 4 months. Each input as an integer. For example, a start date of March 31st 2019 would be: from_date_day = 31 from_date_month = 3 and from_date_year = 2019
For example, I something like this would kind of work:
((Math.abs($('#to_date_month').val() - $('#from_date_month').val()) > 2) && $('#from_date_day').val() <= $('#to_date_day').val()
return "error"
The problem with this code is that it doesn't work when the dates straddle two different years. I'm using coffeescript, but a solution in jquery or js would also work.
I'd recommend creating two Javascript Date objects of those two dates. This can be done by feeding the year, the month and finally the day to the constructor of the Date object.
e.g.
var startDate = new Date(2019, 1, 16); // January the 16th
var endDate = new Date(2019, 3, 30); // March the 30th
Using the .getTime() function of the Date object you can get the number of milliseconds passed since 1.1.1970. If you calculate the difference between those two numbers, wrap it inside Math.abs() and divide that number by 1000, 60, 60 and finally 24 you get the number of days. If this number is bigger than ~120, the range is more than four months.
console.log(Math.abs(startDate.getTime() - endDate.getTime()) / 1000/60/60/24);
In your use case the Date object could be set like this:
var startDate = new Date(parseInt($('#from_date_year').val()), parseInt($('#from_date_month').val()), parseInt($('#from_date_day').val()));
This question already has answers here:
Add one day to date in javascript
(11 answers)
Closed 4 years ago.
I have From-Date, To-Date, and Total-Days...if i have a From-Date and Total-Days then i have to calculate To-Date automatically
I Used The Following method to get the To-Date day
var FromDate = $("#FromDate").val();
var TotalDays = $("#txtDays").val();
FromDate.setDate(parseInt(FromDate.getDate()) + parseInt(NoOfDays));
var dd = FromDate.getDate()-1;
This Will Not Work For Day 1 of every month.....Since It Returns 0
How To Handle This Situation or help me to solve this in another way....Thanx In Advance
try this
var d = new Date('08-20-2018');
d.setDate(d.getDate() - 1);
alert(d.getDate());
Date object is smart enough to know what to do if you set any of the "components" (month, day, hour, minute, second, millisecond) outside of "normal" range - it does the maths for you
If you only need to know the previous date, you can always subtract the 24hours from the epoch time and then convert it back to date object and get the date like:
new Date(new Date('08-01-2018').getTime() - 24*3600000).getDate()
new Date('08-01-2018').getTime() will give you the epoch time of the date you want previous date from
24*3600000 is subtracting the 24 milliseconds from the epoch
After subtracting the value you get the previous day epoch and using the new Date() constructor you are getting the Date object again
On this new date object you can call getDate() method to get the correct result of 31.
I have given date to Date constructor in MM-DD-YYYY format
I want to count down the days until a particular event using momentjs but I'm getting an unexpected result.
With today's date being 17th April, and the event date being 14th May, I want the resulting number of days to be 27, however my code gives me a result of 57. What's wrong?
function daysRemaining() {
var eventdate = moment([2015, 5, 14]);
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());
When creating a moment object using an array, you have to take note that months, hours, minutes, seconds, and milliseconds are all zero indexed. Years and days of the month are 1 indexed. This is to mirror the native Date parameters.
Reference
So either change the month to 4 to reflect May or parse the date as an ISO 8601 string
function daysRemaining() {
var eventdate = moment("2015-05-14");
var todaysdate = moment();
return eventdate.diff(todaysdate, 'days');
}
alert(daysRemaining());
Just to add for anyone else that comes across this - there's actually a helper that does the phrasing etc for you:
https://momentjs.com/docs/#/displaying/to/
/* Retrieve a string describing the time from now to the provided date */
daysUntil: function(dateToCheckAgainst){
return new moment().to(moment(dateToCheckAgainst));
}
// Sample outputs
"in three months"
"in two months"
"in 25 days"
That's because months are zero indexed. So 5 is actually June ;)
I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');