angularjs date timezone adjustment issue - javascript

What I want to do is print date in below format in angularjs.
Aug 30, 2016
{{CC.StartDate | date }} //angularjs UI code
I am just sending the modal with response, which will automatically deserialize object into json.
List<CClass> Items = CClass.GetMultipleAsObject(); //fetch data
return Request.CreateResponse(Items); //sending it to UI
I can see that I am receiving "2016-08-30T00:00:00" in response in network tab. But when it gets rendered in different browser, it renders it differently.
I am in IST timezone, Chrome render it as "Aug 30, 2016". But IE and FF render it as "Aug 29, 2016". In PST timezone all browser render it correct. Date looks like in UTC.
I tried converting it into a plain string, still same issue.
Tried this - $filter('date')(input, "yyyy-MM-dd");, still same issue
I haven't tried momentjs, thought it must be possible without that also.
Can someone guide, how I can I get rid of this timezone localization and just show date in string ire-respective of timezone?

Date is always tricky with javascript. In your scenario you need to display the date without involving timezone. You can use getUTCDate() getUTCMonth() and getUTCFullYear() to get the individual elements from your date string and construct a new date object.
Following example returns the same date in both ie and chrome.
JSFiddle link
Hope this helps.

Related

DateTime Filter AngularJS not Giving Correct Date?

I am using backend as Tomcat which gives me timestamp as follows :-
1448966450000 If I use the website to convert this time to datetime it gives me something like below :-
1448966450000 -> Wed, 02 Dec 47885 00:33:20 GMT
But when I use a Filter for AngularJS it gives me something like this:-
{{1448966450000 | date: "MMM dd,yyyy '#' hh:mma"}} -> Dec 01,2015 # 04:10PM
I am living at India and according to IST the time which I receive with the filter is pretty wrong. I am not able to understand where the problem lies.
NOTE: Date Shown by angular is wrong while the former one is the correct one.
Take a look at your timestamp, your site needs timestamp in seconds, but angular filter accepts milliseconds, so you need to multiply your timestamp in filter on 1000, you need to enter 1448966450000000, not 1448966450000
Check the timezone: add timezone to output format (Z)
If timezone is not suitable for you, set preferred timezone
{{1448966450000 | date: "MMM dd,yyyy '#' hh:mma" : '+0530'}}
For more information see https://docs.angularjs.org/api/ng/filter/date
The timestamp you are using is in milliseconds since 1/1/1970
The angular filter does it right.
The website you test it wants the timestamp in seconds.

momentjs: how to get the date in a specific timezone

In a nutshell I want moment to respect server's timezone. I've set my machine's timezone to Alaska but I'm passing a Brisbane timezone string to moment. Now I need moment.toDate to return a date instance in the same timezone as the one I pass in the moment constructor; e.g.
m = moment("2016-11-20T08:00:00+10:00")
m.format() // "2016-11-20T08:00:00+10:00"
m.toDate() // Sat Nov 19 2016 13:00:00 GMT-0900 (AKST)
I want to get a Date instance from moment that's in the input timezone; e.g. somehow get toDate to return Sun Nov 20 2016 08:00:00 GMT+1000 (AEST).
FWIW I have tried the same code with and without moment.tz.setDefault and while it correctly changes the format result, toDate always uses the machine's timezone!
Update
The reason I need this behaviour is that some JavaScript libraries and controls don't understand moment and only work with Date and the time/date gets skewed when presented back by them. One example, the one I'm currently dealing with, is jQuery UI date picker control. I want the date picker to show the current date as it's on the server (or on a specific timezone).
Thanks in advance.
The Date object represents the time in UTC internally, and can only use the time zone of the machine its running on when projected.
There's absolutely no way to produce a Date object that uses an arbitrary time zone. Any examples you may come across that try to manipulate the Date object (such by adding or subtracting time zone offsets) are fundamentally flawed.
Moment itself has great time zone support, including the moment-timezone extension for working with named time zones instead of just time zone offsets. But once you go back to a Date object - you're back at the mercy of the behavior of that object.
Sorry, but there's no way to achieve what you are asking. Perhaps you could elaborate as to why you wanted to do this, and I could recommend a workaround.
Update: With regards to your update, usually there is a mechanism for getting the value from a date picker as text, rather than as a date object. With the example of the jQuery UI date picker control, the onSelect event gives it to you as text already, or you can simply call .val() instead of .datepicker('getDate') to get the text out of the field. Once you have a textual value, you can then parse it with moment however you like.
Similarly, when setting the value, you don't necessarily need a Date object. You could just set the value of the textbox as a string, or you can pass a string to the setDate function.
In most cases, you won't have to go through a Date object. But if for some reason you do, then you'll need to artificially construct one with something crazy like:
var d = new Date(m.format('YYYY/MM/DD'));
Normally, I'd be against that - but if it's just there to get the pass a value to a UI control, then it's probably ok.
This will get you a moment in the same timezone as the moment string, but toDate is always in the local timezone.
d = "2016-11-20T08:00:00+10:00"
m = moment(d).utcOffset(d)
m.format()
m.toDate()

AngularUI Datepicker without filter, what's happening?

I was using a angularUI datepicker in my webapp when I suddently came across this:
http://plnkr.co/edit/MLnWCtYHMNqLeuFOetWH?p=preview
In particular I am setting the date in my controller like this:
$scope.getDate = function() {
$scope.dt = new Date(2015,0,1);
};
$scope.getDate();
then in my html I display the date in this two ways:
<pre>With angular date filter date is: <em>{{dt | date:'medium' }}</em></pre>
<pre>Without angular date filter is: <em>{{dt}}</em></pre>
As you can see in this plunker, I have selected the date "01/01/2015" (january 1st, 2015) and if I see the plunker with the Angular date filter I get the correct date and time.
However, if I remove the filter, I get the same date 1 hour in the past.
It is surely a problem of timezones, but I cannot find any sources of this behavior, so I wanted to understand what's going on. Is there any explanation or a website to browse?
Also, what will arrive at the server? Do I have to do some special formatting on the server? (i cannot test this atm)
Don't know if this matters (I think yes), but my browser lives in Italy.
Both displayed dates are the exact same moment. They are just formatted differently. When you instantiate a date, your browser uses your current timezone (1st of January 2015 at midnight in Italy, so UTC+1).
When using a date filter, Angular displays your date in your current timezone whereas it displays the UTC date without.
Just try:
var date = new Date(2015,0,1);
date.toString(); // -> "Thu Jan 01 2015 00:00:00 GMT+0100 (CET)"
date.toISOString(); // -> "2014-12-31T23:00:00.000Z" (Z means UTC time)
As a rule of thumb, always use ISO8601 date format when sending your dates to the server (it is what JSON.stringify does when serializing an object with date values).

MVC, JsonResult, DateTime and the Timezone

Good Day my fellow programmers,
I now have spent 2 days looking for a solution, and are about to go crazy..
That's the Problem:
On The WebPage, the User modifies an object, and i need to store the time without timezone info.
[ i just care about hours and minutes ]
the object is postet to the Server [ asp.net mvc 5] via ajax as a JsonResult.
Let's say, Server has Timezone UTC + 1 , User selects 09:00 on the webpage, json is ajax't to my controller, and boom - the resulting Object in my mvc controller has a DateTime Object with a time of 10:00 ;
What i have done: Client-side: Store Time Info in UTC Format [so a dateobjet.toUTCString() gives me the correct date i want to have, just before postig to the controller]
So is there a way to tell the JsonResult-Converter to just ignore the Timezone-Info and use the UTC-Time?
Thanks,
Mr.Muh
OK, i hope to describe it in a better (and shorter):
ClientSite: JavaScript date with the time i need in UTC (but still with some timezone information, which i don't need), let's say e.g. 'Fri, 01 Feb 1980 09:00:00 GMT' as a result from .toUTCString()
Get's wrapped up together with other variables in some Json & posted via ajax to my asp.net mvc 5 controller
ServerSide: Controller has my C# - Class as Argument (so automatically converting Json-Object to C# - Class), but the resulting DateTime part now says 10:00:00 due to my server TimeZone set to UTC+1.
So, How can i get the correct UTC time stored to my C# DateTime ?
Thanks :)
If I understand you correctly, you want to ignore the timezone. You can "reset" your DateTime object to UTC (without affecting the actual value) using DateTime.SpecifyKind:
DateTime utcTime = DateTime.SpecifyKind(originalDateTime, DateTimeKind.Utc);

javascript timezone format

I need to format a javascript Date to send via json to the server. The server expects the time to be in the format according to this example
2011-08-31T06:49:28.931 -0700
which it conveniently tells me when I try to submit something like
2011-08-31T06:49:28.931 -07:00
The trouble I am having is with the timezone part, -0700. I've been looking at the Date API, and don't see a way to specify the timezone format. I can do d.getTimezoneOffset, but it returns 240 (Im in EDT I think) for me.
So, I can convert 240 to 0400 to represent 4 hours. I am worried however about correctness for other timezones. My questions are
1) How to convert the result of the getTimezoneOffset() into the required format, and how to determine what the sign should be (thats the part I am worried about)?
2) Is there a way to get the format off the date object itself so I don't have to do anything custom? If i do d.toString() I get "Wed Aug 31 2011 09:48:27 GMT-0400 (EDT)", so here the timezone part is in the format I want. So it might be possible. Maybe the best solution is to just use a regex to grab the timezone off d.toString()...
3) Extra credit: is the format the server requires some sort of standard?
Update: using match(/^.*GMT(-?\d*)/) returns "-0400" at index 1 of the array. Perhaps I should just use that? Im wondering if that regex will work for all timezones in the context of the sign.
Try this code:
var d=new Date(Date.now()); // sets your date to variable d
function repeat(str,count) { // EXTENSION
return new Array(count+1).join(str);
};
function padLeft(str,length,char) { // EXTENSION
return length<=str.length ? str.substr(0,length) : repeat(String(char||" ").substr(0,1),length-str.length)+str;
};
var str=padLeft(String(d.getFullYear()),4,"0")+"-"+
padLeft(String(d.getMonth()),2,"0")+"-"+
padLeft(String(d.getDate()),2,"0")+"T"+
padLeft(String(d.getHours()),2,"0")+":"+
padLeft(String(d.getMinutes()),2,"0")+":"+
padLeft(String(d.getSeconds()),2,"0")+"."+
d.getMilliseconds();
//str+=" GMT";
var o=d.getTimezoneOffset(),s=o<0?"+":"-",h,m;
h=Math.floor(Math.abs(o)/60);
m=Math.abs(o)-h*60;
str+=" "+s+padLeft(String(h),2,"0")+padLeft(String(m),2,"0");
alert(str);
You might want to use one of the date/time formatting libraries that bakes in support for this timezone format (such as http://jacwright.com/projects/javascript/date_format/). In any case, you're right: there really is no good way to control the format output.
As far as the regex goes I don't know that all browsers consistently use the GMT string format, so that may not be the best path forward.

Categories

Resources