JS how to get month, week, past 3 days from today - javascript

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.

Related

How to get a date time object in UTC that is the last time it was a certain time

I need to make sure if its after 21 hours in UTC or 4 pm est to set the initial day in the date picker as the next day although i need help with the logic of getting a date time object of the last time when it was last 21 hours in UTC.
For example if its 22 hours in utc the last time it was 21 hours was a hour ago so i just use the same utc date and subtract a hour
although a couple hours after it will be a new utc date how do i represent that? Does any one have any ideas?
Im using datetime and using custom color picker libraries is not the solution i'm interested in. I just need help on the logic of how to set Initial date/ Current date in my custom calendar picker with the criteria that after 21 hours utc it should move to the next day.
You just need to test the UTC hour, which is returned by getUTCHours, so:
function getDate(date = new Date()) {
// Copy date so don't affect original
let d = new Date(date);
// If 2100 UTC or later, set to tomorrow UTC
if (d.getUTCHours() > 20) {
d.setUTCDate(d.getUTCDate() + 1);
}
// Set the time to 2100
d.setUTCHours(21,0,0,0);
return d;
}
// Current value
console.log(getDate());
// Value for 2021-03-01T22:00:00Z
console.log(getDate(new Date(Date.UTC(2021,2,1,22)))); // T21:00:00.000Z

JavaScript Elapsed time since a previous date/time [duplicate]

This question already has answers here:
How to calculate date difference in JavaScript? [duplicate]
(24 answers)
Closed 4 years ago.
I have been trying to calculate the exact time since a very specific date in history using Javascript.
The Date is Feb 24th 2008 17:30 GMT+0
I need help in calculating exact time passed down to the second using Javascript.
Here is the previous date and the current date.
I need help in calculating Hours, Minutes and Seconds since that date/time.
var previousDate = new Date("Sun Feb 24 2008 17:30:00 GMT+0");
var currentDate = new Date();
It's easy to calculate the milliseconds between two dates:
var millis = currentDate - previousDate;
From there you can calculate the seconds:
var seconds = Math.round(millis / 1000);
Calculation of minutes, hours, ... is straightforward (division by 60 or 60*60).
Parsing of date strings in javascript fraught. If you have a specific date, far better to avoid the built–in parser. If it's UTC, use Date.UTC to generate the time value.
Then just subtract from any other date to get the difference in milliseconds and convert to seconds, as hgoebi suggests.
var epoch = new Date(Date.UTC(2008,1,24,17,30));
console.log(epoch.toISOString());
console.log(`Seconds from epoch to now: ${(Date.now() - epoch)/1000|0}`);

Javascript For Display Previous Day From Given Date [duplicate]

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

Adding to Epoch to find new Date in Javascript

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)))

Calculate days to go until a particular date with momentjs

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 ;)

Categories