Javascript setting date not working, showing wrong hour - javascript

I want to set date and time to 2016-05-11T00:00:00.000Z
var date = new Date(2016,4,12,0,0,0,0);
but instead of showing Date 2016-05-11T00:00:00.000Z its giving Date 2016-05-11T19:00:00.000Z
I want time 00:00:00 but its giving 19:00:00

Use Date.UTC:
Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments. [Source]

Related

moment.js returns different timezones

I'm using this code to create 2 dates that represent a filter date range (in this case the last 3 months):
$ctrl.startDate = moment().utc().startOf('month').add(-2, 'months').toDate();
$ctrl.endDate = moment().utc().endOf('month').add(0, 'months').toDate();
However the first returned date is timezone CET (GMT+1) (which is my zone) and the second is CEST (GMT+2). I have no idea why! I have tried using utc() to get "neutral" dates without success.
Returned dates:
01.01.2017 01:00:00 CET
01.04.2017 01:59:59 CEST
I want either GMT or CET but the same zone! Where does moment take these 2 zones from?
I've come so far that I think it is a bug.
I use version 2.17.1
Any ideas?
JSFIDDLE:
https://jsfiddle.net/FLhpq/8807/
I don't know if you can consider it a bug, in your fiddle you are showing in the result of toDate() that as docs says:
get the native Date object that Moment.js wraps
If you look at momentjs the code you will see that toDate() implementation:
function toDate () {
return new Date(this.valueOf());
}
simply uses new Date() that returns a JavaScript date object in local time, see MDN Date:
Note: Where Date is called as a constructor with more than one argument, the specifed arguments represent local time. If UTC is desired, use new Date(Date.UTC(...)) with the same arguments.
If you use format() in your code you will always see +00:00 offset.
var divUtc = $('#divUTC');
var divLocal = $('#divLocal');
var startDate = moment.utc().startOf('month').add(-2, 'months').format('YYYY-MM-DDTHH:mm:ssZ');
var endDate = moment.utc().endOf('month').add(0, 'months').format('YYYY-MM-DDTHH:mm:ssZ');
//put UTC time into divUTC
divUtc.text(startDate);
divLocal.text(endDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.7/moment-timezone-with-data-2010-2020.min.js"></script>
UTC<br/>
<div id="divUTC"></div><br/>
Your Local Time with respect to above UTC time<br/>
<div id="divLocal">
</div>

JavaScript Date formatting and conversion issue

I'm located in PST timezone and I want to be able to take the string "2014-01-01" and convert it into Unix time without "2014-01-01" getting converted to PST.
Here's what I'm doing:
Date.parse(new Date("2014-01-01"))
I'm getting the value 1388534400000 which is equivalent to Tue Dec 31 2013 16:00:00 GMT-0800 (Pacific Standard Time)
I want to take the date as "2014-01-01" and not convert it into PST before converting it into Unix time.
A few things:
The Date constructor returns a Date object, not a string. You shouldn't wrap it in a call to Date.parse.
If you want a unix timestamp, just call getTime().
var ts = new Date("2014-01-01").getTime();
Alternatively, you can parse the date string without creating a Date object at all.
var ts = Date.parse("2014-01-01");
The behavior of date parsing in JavaScript is implementation dependent. Most browsers will already interpret a yyyy-mm-dd string to be in UTC, due to the dashes (-). If you replace with with slashes (/), you'll see the string get interpreted as local time instead.
I think you're confused about the output. You said the timestamp was equivalent to PST, but that's just one representation. It's also equivalent to the UTC value you passed in. It's not getting converted in the input, it's being converted when you are converting the timestamp back to local time.
You can use a library like moment.js, which gives you full control of the input and output. This is usually the best option, but has the overhead of including a library in your application.
Another way to convert the specified date string to Unix time is as follows:
var str = "2014-01-01";
var parts = str.split('-');
parts[1] -= 1; // js numeric mos are 0-11
var ms = Date.UTC( parts[0], parts[1], parts[2] ); // parts: YYYY, MM, DD
var unix_time = ms/1000; // Unix time uses seconds
console.log("Unix time: " + unix_time);
Date.UTC() returns the number of milliseconds occurring since January 1, 1970 midnight up to the instant of the specified date, irrespective of any timezone. The script transforms the result into Unix time, i.e. seconds, by dividing the number of milliseconds by 1000.
After splitting the string into an array, the code adjusts the element containing the month, lest JavaScript mistake its value for March; JavaScript comprehends numeric months as ranging from 0-11, not 1-12. Next, the script passes the elements sequentially in accordance with the year, month, day parameters that Date.UTC requires. Although UTC() expects numbers for parameters, it accepts the numerical strings.
Note: if you first create a new date object and expect to use a UTC method -- that results in an error because it is a static method of JavaScript's Date Object.
You may check the validity of the UTC() return value, using the aforementioned variables ms and str, as follows:
console.log( new Date( str ).toUTCString( ms ));
The output: Wed, 01 Jan 2014 00:00:00 GMT
See live demo here)
Passing a date string to the Date constructor instead of the numerical parameters it expects affords an unexpected benefit; the date string is treated as if it's timezone is UTC, i.e. zero by the local date object. Once created, the local date object executes its toUTCString() method to attain the above-indicated result. The toString() method would also yield the same output, but it appends local timezone information.

Dates display behind by a day

I'm encountering some weird behavior while using Moment.js. I have some helper classes attached to the Date prototype, which are apparently are causing each date to display behind by a day.
Date.prototype.format = function(){
return moment(this).format('MM/DD/YYYY')
}
var date = new Date('2008-05-13T00:00:00')
date.format() // => 05/12/2008, but should be 05/13/2008
A couple of other weird things I've noticed:
date.getDate() // => yields 12, but should be 13
But, if I instantiated the Moment object directly with the UTC string, then it works:
moment('2008-05-13T00:00:00').format('MM/DD/YY') // => 05/13/08
But I'm dealing with plain date objects, and modifying every date to a Moment object isn't my favorite idea. I have already tried modifying the format function to extract the UTC string from the date and see if it displays correctly then, but to no avail.
date.toUTCString() // => Correctly yields "Tue, 13 May 2008 00:00:00 GMT"
moment(date.toUTCString()).format('MM/DD/YY') // => still 05/12/08
Any ideas what's happening here? Is there a problem with the date constructor?
EDIT: Outputting the time as well:
moment(date).format('MM/DD/YY hh:mm:ss') // => "05/12/08 08:00:00"
You have to tell moment.js that you to display the date in UTC:
moment(this).utc().format('MM/DD/YYYY')
More in the documentation: http://momentjs.com/docs/#/parsing/utc/
But, if I instantiated the Moment object directly with the UTC string, then it works:
moment('2008-05-13T00:00:00').format('MM/DD/YY') // => 05/13/08`
Moment.js interprets the argument as local time:
By default, moment parses and displays in local time.
Whereas new Date() (and Date.parse) interpret the value as UTC time:
The parse function [...] interprets the resulting String as a date and time; it returns a Number, the UTC time value corresponding to the date and time.
I have already tried modifying the format function to extract the UTC string from the date and see if it displays correctly then, but to no avail.
date.toUTCString() // => Correctly yields "Tue, 13 May 2008 00:00:00 GMT"
moment(date.toUTCString()).format('MM/DD/YY') // => still 05/12/08`
The format that date.toUTCString() yields is not in any of the formats that moment.js supports, so it falls back to using new Date() (which interprets the string as UTC time, not local time).

DatePicker Error in Angular JS due to UTC

I have selected the 12th of September 2014 in the UI.
Following is the code
ctrl.$formatters.push(function (modelValue) {
console.log(modelValue);
var dt = new Date(modelValue);
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset());
console.log(dt)
return dt;
});
The two console logs i see are the following.
09/11/2014
Wed Sep 10 2014 18:30:00 GMT+0530 (IST)
Am not sure why the conversion from UTC to local is not carried out correctly.
Thanks in advance.
Its not clear what you are trying to do. The input does not have a time. Do you want to add the current time of the day to the arbitrary date? Or do you just want a local representation of the date? I'm geussing the latter.
Instead of dt.setMinutes(...) and the following two lines, replace all three lines with:
return dt.toLocaleDateString();
If you ARE trying to set the time to now on whatever date is input (I don't know why...) but you might try:
dt.setTime( new Date().getTime() );
instead of the setMinutes(...) line.
then you can
return dt.toLocaleString;
All date objects are stored as miliseconds since, like 1972. It is best to use the built in Date object methods to get what you want from it. Here are the docs for reference.

format just a time for use with ui-bootstrap timepicker

I have a server returning a time value like so
14:00
The reason for this is it represents the start time of say a task that happens repetively say every monday at 14:00 so the date is irrelevant. I want to display this value to the user when they are editing the task so that they can change it with ui-bootstraps timepicker.
The timepicker requires either an epoch, an rfc2822 or ISO 8601 date so I need to just add a random date that I can discard later for the timepicker to be able parse and display the value (which seems ridiculous seen as it is a time picker not a time on a specific day picker but whatever)
so either using the javascript date object or moment.js how can I take that value and create a valid date object with it?
As you requested a moment.js solution also:
var date = moment("14:00", "HH:mm").toDate();
// assume returned is the hours and minutes you get in this format: 14:00
hourData = returned.split(':');
var date = new Date();
date.setHours(hourData[0]);
date.setMinutes(hourData[1]);
date will be something like Sat Jul 12 2014 14:00:13 GMT+0300 (EEST)

Categories