Javascript, Time and Date: Getting the next day, week, month, year, etc - javascript

Based on a given millisecond timestamp, what's the 'correct' way to get the next day, week, month, year, etc.? That is, without having to do some kind of binary search with raw millisecond timestamp values or something silly like that.
Edit: Does using the Date constructor with a month, day, hour, etc. value beyond the limit translate it to the next year, month, day, etc.?

function getNextDate()
{
var today = new Date();
var d = today.getDate();
var m = today.getMonth();
var y = today.getYear();
var NextDate= new Date(y, m, d+1);
var Ndate=NextDate.getMonth()+1+"/"+NextDate.getDate()+"/"+NextDate.getYear();
alert(Ndate);
}

If the millisecond timestamp that you have is (conveniently!) the number of milliseconds since 1970/01/01 then you can simply create a new Date object from the millisecond value new Date(milliseconds) and use it as outlined in Misnomer's answer.
If your timestamp is based from onther point in time then you can simply workout the offset (in milliseconds) from 1970/01/01 and subtract that from the timestamp before creating the Date object.
As always when dealing with dates, be clear if you are dealing in local or UTC times.
w3schools date object
w3schools full date reference

Related

JS: Convert Today's Date to ISOString() with Fixed Time

I'm trying to convert today's date to an ISO standard string but with the fixed time of T00:00:00.000Z.
I can get as far as returning a ISO string of today's date and time:
var isoDate = new Date().toISOString();
// returns "2015-10-27T22:36:19.704Z"
But I wanted to know if it's possible to have a fixed time, so it should return:
"2015-10-27T00:00:00.000Z"
Is this possible?
Any help is appreciated. Thanks in advance!
To get the current UTC date at midnight:
var d = new Date();
d.setUTCHours(0);
d.setUTCMinutes(0);
d.setUTCSeconds(0);
d.setUTCMilliseconds(0);
var output = d.toISOString();
To get the current local date, with the time portion set to UTC midnight:
var d = new Date();
var ts = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
var output = new Date(ts).toISOString();
As for which to use, think through your requirements very carefully, The current UTC date and the local date may indeed be two different days.
For example, when it's midnight (00:00) October 27th in UTC, it's 8:00 PM on October 26th in New York.
Also, consider using moment.js, which makes operations like either of these much easier with the startOf('day') and .utc() functions.

Create now/subtract dates/month with format of "2014-08-04T17:19:00-07:00" in JavaScript

How do I create the time now and format it to a string with format of "2014-08-04T17:19:00-07:00"? Using moment.js or any other JavaScript?
I will also need to create 2 new, one to subtract a week from now, one to subtract a month from now, but also with this format.
Simply enough:
var d = Date.now(); //For current time in MS
d = new Date(); //For current time wrapped in the object.
d.toISOString();
For more on ISO String read this or that.
If you want to do any Date arithmetic, like adding a month, just add/subtract the number of milliseconds for that unit to your date object.
Additionally, if you don't want time in Zulu, you can use String manipulation to drop the Z and add the proper zone. Don't forget to account for the difference in time zones!
You can do this:
var date = new Date();
date.toISOString();
> "2014-08-05T17:22:08.030Z"
// Subtract one week:
var before = date;
before.setDate(date.getDate()-7);
before.toISOString();
> "2014-07-29T17:22:08.030Z"

Milliseconds for current date in javascript

When I try the following
new Date().valueOf()
the result is 140082670954. For
new Date('05/23/2014').valueOf()
the result is 1400783400000.
There is a difference in the millisecond outputs. The second one is at 00:00:00 hrs but the first one is at 12pm with todays date.
I need to get the milliseconds as in the second one. How would I do this dynamically?
When you do:
new Date()
a new Date object is created with a time value for the current instant. When you do:
new Date('05/23/2014')
a new Date object is created at 00:00:00.000 on the specified date. If you want the equivalent using the constructor, then create the Date and set the time appropriately:
var d = new Date();
d.setHours(0,0,0,0);
NB
Please don't pass strings to the Date constructor. It calls Date.parse which is largely implementation dependent and inconsistent across browsers (even using the string format specified in ES5). Call the constructor with the required values:
new Date(2014, 4, 23);
noting that months are zero indexed so May is 4.
I take it that you want the milliseconds from midnight of a given day? I am afraid it won't be too simple, thanks to JavaScript's very constrained date-time API. You can extract the year, month, and day from the date object and create a new object from those:
var now = new Date();
var day = now.getDate();
var month = now.getMonth();
var year = now.getFullYear();
var today = new Date(year, month, day);
var millis = today.valueOf();
BTW: You mention that the first one "is at 12pm" - that depends on at what time you execute the statement. new Date() gives you the date including the current local time. So it appears that you tried it at roughly 12pm :-)

Comparing today's date with another date in moment is returning the wrong date, why?

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

How to get the current seconds in the current month?

I am trying to calculate the current second in the current month, but I'm having trouble creating a simple function that does it.
My best guess involves using getTime() - the current milliseconds since January 1 1970 - and then subtracting X, where X is the number of milliseconds up to the end of the previous month.
Can you help me think of a better way to do this?
Thank you very much for your help.
Cheers,
function() {
var now = new Date().getTime(),
monthStart = new Date();
monthStart.setDate(1);
monthStart.setHours(0);
monthStart.setMinutes(0);
monthStart.setSeconds(0);
monthStart.setMilliseconds(0);
return Math.floor((now - monthStart.getTime()) / 1000);
}
You can create a Date instance and then call methods to set everything back to 00:00:00 on the first day of the month. Then you'd subtract that from the "now" timestamp.
The methods you'd call are setDate(1) to set the day-of-month back to the start of the month, and then setHours(), setMinutes(), setSeconds(), and setMilliseconds(), passing all those zero.
Timestamps (return values from getTime() are in milliseconds, so you'll divide your difference by 1000 to get the seconds into the month.
You can create a new date set to the first day of the month, like so:
var start = Date.parse("2010-11-01");
Then you can create a date for today:
var today = Date.now();
Then you just subtract them:
var seconds_in_month = today - start;

Categories