convert timestamp Date to javaScript date - javascript

in fact, I called my java services from AngularJS and I go back an object that contains a date, for example:
{
"Name": "Jhon"
"date": 1465826400000
}
in my service java 1465826400000 date corresponds to Monday, June 13, 2016 14: 00 UTC and in my Javascript code:
var date = new Date (1465826400000);
and it gives 14-06-2016 4:00:00
that means one day lag between the two dates.
someone has an idea

No, it just means you're looking at the result in the local timezone of your browser. If you look at it as a UTC date, it matches:
console.log(new Date (1465826400000).toISOString()); // "2016-06-13T14:00:00.000Z"

Related

getDay() doesn't work client-side after having sent date to the server

This works perfectly fine on the client-side, at first:
var timeOfMessageSent = new Date();
console.log(timeOfMessageSent); // Mon May 22 2017 14:03:13 GMT+0200 (Romance Summer Time)
var day = timeOfMessageSent.getDay(); // 1
console.log("this is the day: ",day);
However, after having sent the date to the server, and then sent it back to the client, it doesn't work.
Now the date is displayed like this: 2017-05-22T12:03:13.437Z
I guess that's why getDate doesn't work.
How do I make sure that the date is displayed like at first? e.g. 2017-05-22T12:03:13.437Z
Make your server date string to date object.
var timeOfMessageSent = new Date();
console.log(timeOfMessageSent); // Mon May 22 2017 14:03:13 GMT+0200 (Romance Summer Time)
var day = timeOfMessageSent.getDay(); // 1
console.log("this is the day: ",day);
var newDate = new Date("2017-05-25T12:19:55.982Z"); // give your server date and return as date object
var newDay = newDate.getDay();
console.log("this is the new day: ", newDay);
It seems the date gets returned by the server as an ISO string. You have to create a new Date instance from this string.
Using strings to create date objects are usually discouraged, but an ISO date string is standard and the safest date string format to initialize a date object from.
A Javascript date object is not something that can be part of JSON, so it needs to be converted to a string or a number in order to be transmitted through a JSON API. That's why the server returns this ISO string representation of the date.
An alternative to ISO string commonly used by JSON APIs is to convert the date to a number representing the milliseconds of the date. Both varieties can be converted back to a Javascript date object with the date constructor: new Date(dateValue)
The ISO string you get back can be modified to your preference using moment.js. With that library you can show the date however you want.

How to convert all dates from UTC to Local time using angularJS?

I have very complex structure that I receive from server-side code.
This structure has many Date properties (of type Date).
These Date properties contain dates in UTC.
I need to convert all of them to Local.
Is there any way to do this in angularJS?
Instead of doing this one-by-one?
Maybe some global setting or options that will instruct angular to convert dates into Local automatically?
Thanks.
append " UTC" to the backend time and run that through new Date(). It'll give you the local time offset.
var backEndDate = "2016-10-20 10:00 AM" + " UTC";
console.log(new Date(backEndDate));
The first approach is change your web service to return the utc date using ISO 8601 format.
For example: "2016-10-07T22:01:00Z"
If the web service return's the date using this ISO is easy to represents the date in local time of user because the browser instances the date based on your current time zone.
For example: if i open my browser console and run this javascript code:
new Date("2016-10-07T22:01:00Z")
I will receive the date based on my time zone, that is GMT-0300.
Fri Oct 07 2016 19:01:00 GMT-0300 (SA Eastern Standard Time)
So, for angularjs code you just need write::
{{"2016-10-07T22:01:00Z" | date}}
i will receive this result:
Oct 7, 2016
Check the filter for date here
For use the filter correctly. For example:
{{"2016-10-07T22:01:00Z" | date: 'MM/dd/yyyy HH:mm'}}
The result is:10/07/2016 19:01
The second approach is convert the date from your web service for the ISO 8601 format.
Actually i had the same problem and the client web service sends me the date just like this: "2016-10-07 22:01:00"
So, i wrote a simple code to convert this date format to ISO 8601.

Javascript Date toJSON() outputting incorrect date

I am based in Australia and while new Date() give me the current date and time in Australia, for instance
Fri Aug 26 2016 09:16:16 GMT+1000 (AUS Eastern Standard Time)
, if I write new Date().toJSON()
I get 2016-08-25T23:20:08.242Z,
how can I get the same format as in yyyy-mm-ddThh:mn:ss but keeping my local day and time, ie it should be the 26 and not the 25th.
Edit: when I write programmatically new Date(2016, 11, x) with var x = 31, using toJSON() I have no guarantee to see displayed 2016-12-31 because of timezones, so was wondering is there is a different javascript function that would give me the intended result.
I would use moment.js for that.
var date = moment("Fri Aug 26 2016 09:16:16 GMT+1000");
console.log(moment(date).format('YYYY-MM-DD T hh:mm:ss'));
https://jsfiddle.net/Refatrafi/ys4nu8o9/
toJSON() returns timestamps in ISO 8601 format. Z at the end of string means that used UTC. Date objects in ECMAScript are internally UTC. The specification for Date.prototype.toJSON says that it uses Date.prototype.toISOString, which states that "the timezone is always UTC".
The date isn't wrong, it's in UTC. Without timezone information, yyyy-mm-ddThh:mn:ss is meaningless unless you explicitly want to assume that it's in the AEST timezone.
If you're transmitting the date as a string to be parsed back into some sort of Date-like object later on (by your webserver, for example), there's nothing you need to do. 2016-08-25T23:20:08.242Z unambiguously refers to the same point in time no matter what you use to parse it.
If you're trying to format the date object and display it somewhere, you can extract the different parts of the Date object and build up the representation you want:
function format_date(d) {
var pretty_date = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join('-');
var pretty_time = [d.getHours(), d.getMinutes(), d.getSeconds()].join(':');
return pretty_date + 'T' + pretty_time;
}
As the other answers have pointed out, if you plan on working more with dates, consider using a library that makes it easier. JavaScript doesn't have a very rich API, so you'll have to write more code.

Comparing Date objects correctly

I am using a jQuery UI datepicker to show a range of dates that are available to the user. I get the date ranges from an API in the form of
"DateRanges": [
{
"StartDate": "0001-01-01T00:00:00",
"EndDate": "0001-01-01T00:00:00"
}
]
The problem is that I am running a comparison on the dates in the beforeShowDay API mapping function, but when I try to convert these dates into a JavaScript Date object for comparison, the Date() constructor is converting the dates to local time and therefore causing the date to change.
For example, if I use new Date("2014-08-22"); then I would expect a Date object that was set to 8/22/2014 at 12:00 AM but instead it is showing 8/21/2014 at 5:00 PM PST. Therefore my comparison does not work correctly because of the conversion.
What can I do to force the Date() object to not change to local time when making comparisons?
This happens because the parsing logic defaults to the UTC time zone when you do not supply one. To get the expected time, pass a time zone.
new Date("2014-08-22T00:00:00-0700");
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
This is another tidbit from the docs that might help (depending on how you are generating those dates):
Given a date string of "March 7, 2014", parse assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC. Therefore Date objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted (this behavior is changed in ECMAScript ed 6 so that both will be treated as local).
so you could also use:
new Date("September 11, 2014");
and you will get a date in your local tz (for me the output is: "Thu Sep 11 2014 00:00:00 GMT-0500 (CDT)").

Unexpected results parsing date strings in JavaScript

I'm working on a JavaScript application. I have two different String dates 31/10/2013 and 1/11/2013 and I create an instance of these two dates with new Date(string).getTime();
But it shows this (the same date ) as the result:
console.log(date_s + " after new date " + date );
31/10/2013 after new date Fri Nov 1 00:00:00 UTC 2013
1/11/2013 after new date Fri Nov 1 00:00:00 UTC 2013
You haven't a valid string in you new Date(string)
Some example to initialize dates
var my_date=new Date(2013,10,31)
and all the documentation on http://www.w3schools.com/js/js_obj_date.asp
31/10/2013 is not a valid date string unless you've got maybe some localization going on. To the default localization settings for en-US, it should be 10/31/2013. What your string means is "month 31 of 2013" which pushes new Date('31/10/2013') to be some time in 2015 because that's where it resolves the date due to that "month 31."
If you want an easy solution, try moment.js - a powerful javascript date parser/formatter/validator/manipulator.
In moment, you can parse date with the syntax like this [doc]:
//this will gives you a correct date object
moment('31/10/2013', 'DD/MM/YYYY').toDate();
Else, you can always welcome to split and rebuild the date object.

Categories

Resources