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);
Related
I'm using moment library to convert date into a utc format. here is my date string:
var dateString = "2019-01-31T11:33:16.952+0000";
new Date("2019-01-31T11:33:16.952+0000") // o/p: Thu Jan 31 2019 03:33:16 GMT-0800 (Pacific Standard Time)
since this date is less than a week from today's date, I'm trying to display a text saying "n days ago" instead of actual date. But for some reason I'm getting a future date displayed as "6 days ago" when I do this:
moment.utc("2019-01-31T11:33:16.952+0000").local().fromNow() // shouldnt this display "5 days ago"??
Not sure why moment is not converting the date correctly, any ideas what could be wrong here?
I guess(Considering use of local() converts to your local timezone so time is deducted because you might be in -ve TimeZone) this answer is a solution you're expecting:
Ideally, you would want to pass a UTC timestamp from your server to
the client. That doesn't mean you have to switch your whole server
over to UTC, it just means that you would convert from the time in
your database to UTC on the server before sending it over the web.
Sure, it would be even better if you actually stored times in UTC, but
you said you aren't in a position to make that sort of change right
now. But let's just work off the assumption that you can't change
anything at all on the server.
We'll also assume that your server is fixed to the UTC-07:00 offset.
In real life, this would only be true for places like Arizona that
don't follow daylight saving time. So if you are in Los Angeles and
are in Pacific Time, then some of your data is based on UTC-07:00, but
some of it is based on UTC-08:00. That requires a lot more work if you
want to do it in JavaScript.
Let's also assume that the input is already a string in ISO8601
format. (If it's not, then let me know and I will adjust this code.)
var s = "2013-09-11 18:00:00"; // from action.timeStamp
var actionTime = moment(s + "-07:00", "YYYY-MM-DD HH:mm:ssZ");
var timeAgo = actionTime.fromNow(); The reason your other code didn't
work is because in the first line, you are affected by the time zone
of the browser. The zone setter in the second line just changes the
zone for formatting, not changing the actual moment in time.
Also, when you dump a moment to the console for debugging, make sure
you format it for output. Otherwise you are just looking at its
internal property values, which may or may not make sense directly.
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.
I have a bunch of date fields (not datetime) in SQL Server. When they are fetched by the web server and sent to the client as JSON a time stamp is appended automatically. So instead of receiving just 2016-09-27 I get 2016-09-27T00:00:00.
When the user interacts with the uiBootstrap calendar control it automatically parses that string into a javascript date object and applies a 4 hour offset for the timezone. When this is sent back to the server it's sent as 2016-09-26T20:00:00. Now my date is off by a day. Also the next time it's fetched it will happen again. But this time it will start at 2016-09-26T00:00:00 and will roll back to 2016-09-25T20:00:00. Each cycle between client and server loses a day.
How do I keep my dates from changing? I'm looking at moment.js but so far haven't really figured out how it can help me.
EDIT
I've setup a test function to try different methods of converting datetimes back and forth.
console.log('JSONDate: ' + JSONDate);
var dt = new Date(JSONDate);
console.log('JS Converted Date: ');
console.log(dt);
console.log('Date converted back to string: ' + dt.toISOString());
Here's the output:
JSONDate: 2016-10-02T00:00:00
JS Converted Date: Sun Oct 02 2016 00:00:00 GMT-0400 (Eastern Daylight Time)
Date converted back to string: 2016-10-02T04:00:00.000Z
In this example the date is now 4 hours ahead.
EDIT 2
Web server is running .net, specifically WebAPI 2. I'm using Entity Framework 6 to communicate between web server and SQL Server 2012.
Ideally, your dates would be serialized in the JSON as just dates. Instead of 2016-10-02T00:00:00, you'd have 2016-10-02. The problem is that .NET doesn't have a built in Date type. It only has DateTime. There are alternatives, such as LocalDate in Noda Time, as discussed in this answer.
However, assuming you don't want to change anything on the back-end, the way to handle this is just to make sure the input date/time is treated as local time, and never converted to/from UTC. This should be the default behavior when you parse the string into a Date object when the string is like 2016-10-02T00:00:00, but the behavior has changed a few times over the years, so if you are potentially dealing with older browsers, you may get some that interpret it as UTC instead.
As far as output goes, the toISOString method of the Date object always outputs in UTC - which is the source of your conversion error. If you want an ISO8601 string in local time - you'd have to construct one yourself using the various accessor functions (getFullYear, etc.), handling zero-padding, and ensuring months are incremented to be 1-based instead of 0-based.
The easier solution is to use moment.js, which can handle this for you.
var d = moment('2016-10-02T00:00:00').toDate(); // now you have a `Date` object
var s = moment(d).format("YYYY-MM-DD[T]HH:mm:ss"); // now you have a string again
Of course, if you don't need the time portion, you can omit it from the format string and the rest should still work out ok.
You could try getting the offset and applying it back to the date. Something like this:
var d = new Date('2016-09-27'); //Mon Sep 26 2016 20:00:00 GMT-0400 (EDT)
new Date(d.getTime() + d.getTimezoneOffset() * 60 * 1000) //Tue Sep 27 2016 00:00:00 GMT-0400 (EDT)
I have date and time in 2016-06-21T10:00:00-07:00 format which represets 06/21/2016 5 PM in PST, I just want to change this to 06/21/2016 5 PM in EST and vice versa. How can I do it with momentz?
JSFiddle
debugger;
var dateTime = moment('2016-06-21T10:00:00-07:00');
var newDateTime = dateTime.clone();
newDateTime.tz('US/Eastern');
//dateTime = dateTime.utc();
console.log(dateTime.utcOffset());
console.log(newDateTime.utcOffset());
console.log(newDateTime.utcOffset() - dateTime.utcOffset());
//console.log(utc.format());
dateTime = dateTime.add(newDateTime.utcOffset(), 'minutes');
console.log(dateTime.format());
console.log(new Date(Date.parse(dateTime.format())).toJSON());
EDIT:
given input = 2016-06-21T08:00:00-07:00 (PST)
expected output = 2016-06-21T08:00:00-04:00 (EST)
So when I convert that to UTC then it should become
2016-06-22T15:00:00Z for PST
2016-06-22T12:00:00Z for EST
I think you are confused about how ISO8601 format works. This format always represents local time with a time zone offset. Thus 2016-06-21T10:00:00-07:00 represents June 21 2016 at 10 AM in a timezone that is currently UTC-7 (this could be US pacific, among many others).
It sounds like you want to take the local time, but put it in a new timezone. This opens up some interesting questions about why you are receiving the date in the format that you are. If the date is meant to be interpreted as an exact point on the global timeline, then the format you are receiving it in is good. If however, the date is meant to be interpreted as a local time (not relative to UTC), it might be worth considering the possibility that the format of the date needs to be changed at the source. For instance, if you are making an ajax request to an API, and it is returning a date in this format, but that date actually has no relationship to UTC, it would be good to try to change that API to only send the local time (without the offset). If you were able to do that, then the following code would work:
moment.tz('2016-06-21T10:00:00', 'America/New_York').format()
"2016-06-21T10:00:00-04:00"
If you are unable to do that, or if the date is meant to be interpreted as an exact point on the global timeline, but you wish to ignore that in your specific use case, that can be done. You will need to specify a parse format that ignores the timezone offset on your initial time stamp. The code would be as follows:
moment.tz('2016-06-21T10:00:00-07:00', 'YYYY-MM-DDTHH:mm:ss', 'America/New_York').format()
"2016-06-21T10:00:00-04:00"
You might benefit from the material in this blog post, as it covers how ISO8601 format works, and how all of moment's constructor functions work.
Checkout moment().utcOffset() You can pass in the offset as parameter to this function and the date would use that locale.
Assuming you know beforehand the utcOffsets required which in your case are -420 and -240 or -300(EST with DayLightSaving). Below can be done
var dateTime = moment('2016-06-21T10:00:00-07:00');
dateTime.utcOffset(-420).format();
"2016-06-21T10:00:00-07:00"
dateTime.utcOffset(-240).format()
"2016-06-21T13:00:00-04:00"
NOTE: With -04:00, it should 13:00:00 and not 07:00:00 - http://www.timeanddate.com/time/zones/est
EDIT: This answer was posted to the earlier version of question, where same time was needed in different timezones. If it is incorrect, kindly please elaborate on how it is.
Thanks!
I'm wondering if it's possible to use AngularStrap's datepicker without it keeping the user's locale's timezone information. In our application we want to handle Contract objects that have an expiration date.
When adding or editing the contract object, there is a datepicker field for selecting the date. The following thing happens:
The user selects the date (e.g. 2013-10-24)
Angular binds the javascript date object to the ng-model field
The binded date object is in the user's timezone (e.g. GMT+3)
The user submits the form
The date gets sent to the server using Angular's $http service
In step 5 the date is converted to UTC format. The selected date was GMT+3 2013-10-24 at midnight, but the UTC conversion changes the date to 2013-10-23 at 9pm.
How could we prevent the conversion, or use UTC dates during the whole process? We don't want the contract's date to change based on the user's local timezone. Instead, we want the date to be always 2013-10-24, no matter what timezone.
Our current solution was to make small changes to the AngularStrap library so that the date won't change when sent to the server.
If we could get the user's selected timezone in the server, we could make another conversion there, but the server doesn't have that information.
All ideas are appreciated!
The issue isn't AngularStrap. Its just how javascript dates work and how JSON formats them for transmission. When you turn a javascript date object into a JSON string, it formats the string as UTC.
For example, I'm in Utah and it is now 07:41 on 2013-10-24. If I create a new javascript date and print it to the console it will say:
Thu Oct 24 2013 07:41:19 GMT-0600 (MDT)
If I stringify that same date (using JSON.stringify(date), I get:
"2013-10-24T13:41:47.656Z"
which you can see is not in my current timezone, but is in UTC. So the conversion is happening just before the form gets sent to the server when it gets converted from a javascript object to a JSON string.
The easiest way to do it would be to just change the date to a string of your own choosing prior to sending the date to the server. So instead of letting JSON change the date to UTC, (assuming you don't care about the time of day) you could just do something like this:
var dateStrToSend = $scope.date.getUTCFullYear() + '-' + ($scope.date.getUTCMonth() + 1) + '-' + $scope.date.getUTCDate();
That will give you a UTC-based string that looks like '2013-10-24' and then you can send that to the server, instead of the JSON format which includes the time info. Hopefully that helps.
UPDATE: As #Matt Johnson said, there are two ways to do it. You said: How could we prevent the conversion, or use UTC dates during the whole process?. If you want to use UTC, then use my above explanation. If you want to just "prevent the conversion", you could use the following:
var dateStrToSend = $scope.date.getFullYear() + '-' + ($scope.date.getMonth() + 1) + '-' + $scope.date.getDate();
A bit late but I spent my afternoon on this and someone might find it useful.
Another way to do this declaratively is to use the dateType, dateFormat and modelDateFormat attributes. Set these in either the config or the HTML e.g
angular.module('app').config(function ($datepickerProvider) {
angular.extend($datepickerProvider.defaults, {
dateFormat: 'dd-MMMM-yyyy',
modelDateFormat: "yyyy-MM-ddTHH:mm:ss",
dateType: "string"
});
});
DateFormat is the format the date will be displayed to the user in the date picker while modelDateFormat is the format it will be converted to before being bound to your model.
I also had default values coming from the server which I needed to be bound to the datepicker on page load. I therefore had to update the format the server serialized dates in JSON to match the modelDateFormat. I am using Web API so I used the below.
var jsonSettings = Formatters.JsonFormatter.SerializerSettings;
jsonSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss";
The "Angular way" is to use the $filter service to format the date returned by the datepicker.
Example (HTML):
{{inpDate | date: 'dd-MM-yyyy'}}
Example (JS):
$scope.processDate = function(dt) {
return $filter('date')(dt, 'dd-MM-yyyy');
}
Plunker here