Update date time string in Javascript to match current timezone using MomentJS - javascript

I have Javascript based app (using Nativescript) in which I'm using moment to do some time manipulation. My server returns dtae times to me in the following string format "9/14/2016 4:52:20 PM" Which are Not in UTC. Depending on where the user is I would like to change the time stamp of this string to match their time zone. So I'm trying to get a string that would look like this "4:52 PM" in EST or "12:52 PM" if it's pacific timezone. I'm currently trying to do this using MomentJS like in the following way:
exports.dateTimeStamp = function(value) {
var utcDate = moment.utc(value);
var localDate = moment(utcDate).local();
var formatedDate = moment(localDate).format('LT');
return formatedDate;
};
Unfortunately this isn't working correctly. As of now If I try to do this and the user is in ****EST (GMT-4:00)**** and the string value I pass in is equal to "9/14/2016 4:52:20 PM" I'm getting back "12:52 PM" Rather than "4:52 PM" Could some one point out what I'm doing wrong? My thought is in involves the switch to UTC but that seems like it's necessary from what I have read.
EDIT
I've looked into Moment Timezone, but I don't think that will work since my application is global and it seems Timezone requires a hard coded country/city string to be passed into it. In my case Javascript being used in an Android App. So I get the locale and culture info from the device. Maybe I'm just not quite understanding how to use it.

Related

UTC displaying wrong times using moment.js [duplicate]

This question already has an answer here:
Why moment.js treats dash differently from slash?
(1 answer)
Closed last month.
I am trying to save a date and time for different time zones. I have changed my time zone in my chrome dev tools for testing purposes as follows
So for testing, I am trying to save a date time for London as '2023/04/21 23:55' when I save this datetimeoffset into my DB it gets stored as '2023-01-30T23:55:00+02:00'
but now when I try to read the format the date is as follows
var test = Moment(date); //'2023-01-30T23:55:00+02:00'
test = test.utc(true);
var format = "yyyy/MM/DD HH:mm";
return test.format(format);
it returns the date 2023/01/30 21:55. Why is it removing the 2 hours?
The issue is that your datetimeoffset has a timezone associated with it (+02:00). The 2023-01-30T23:55 part of your timestamp is not UTC time, it is local time, and the +02:00 signifies the offset of that timezone.
I'm not sure how you're saving that time in the first place, you probably forgot to specify the timezone as UTC. For example, if the date was created with Moment('2023-01-30T23:55:00'), then it that time will be intepreted as 23:55:00 on 2023-01-30 in the system's timezone, not UTC. To fix this, you need to use the Moment.utc('2023-01-30T23:55:00').

How to save correct time in database?

I have one object called appointment which has two properties: StartDate and EndDate.
When I make POST request I send these values using ISOString time .
this.appointment.StartDate.toISOString()
On the server-side, I received these properties with correct values. Also, it seems to be correct when I create model in order to save appointment to the database. I used .ToUniversalTime() method.
var newAppointment = new Appointment()
{
StartDate =Convert.ToDateTime(model.StartDate).ToUniversalTime(),
EndDate = Convert.ToDateTime(model.EndDate).ToUniversalTime(),
SpecialityId = speciality.Id,
LocationId = location.Id,
PatientId = patient.Id,
UserId = user.Id,
Observations = model.Observations
};
But in database I found another values. Can explain somebody why is this behaviour ?
For instance, I used 2017.09.01 11:00 for StartDate and in database i found 2017-09-01 08:00
The server and database is located in the westeurope.
A few things:
Don't call ToUniversalTime in a web application. It's designed to convert from the server's local time zone to UTC. The server's time zone should be irrelavent to your application. Web applications should never use ToUniversalTime, ToLocalTime, DateTime.Now, TimeZoneInfo.Local, DateTimeKind.Local or any other method that uses the time zone of the computer it's running on.
Ideally, on the server side, your model.StartDate and model.EndDate would already be DateTime objects, because they'd have been deserialized that way. Therefore, you probably don't need to call Convert.ToDateTime. If they are strings, then I would adjust your model class accordingly.
On the client side, assuming StartDate and EndDate are JavaScript Date objects, and they were created using local time values (that is, the time zone of the browser), when you call toISOString, you're not just getting a string in ISO 8601 format - it is also converting it from the browser's time zone to UTC.
In your example, the UTC time is 3 hours ahead of UTC for the date and time shown. From your profile, I see you are located in Romania, which is indeed UTC+3 for this date, because it is currently observing Eastern European Summer Time. When Summer Time ends (on October 29, 2017 at 04:00), it will return to UTC+2. For this reason, you cannot simply add three hours to all values.
If you want to send local time values from the client, you should send them in ISO 8601 format, without any Z or offset, for example 2017-09-01T11:00. There are several ways to achieve this:
The best way is to not have them in a Date object to begin with. For example, if your input uses the <input type="datetime-local" /> input type (as specified in HTML5), the .value property is not a Date object, but rather a string in ISO 8601 format.
If you can't avoid a Date object, then create a local ISO string, like this:
function dateToLocalISOString(date) {
var offset = date.getTimezoneOffset();
var shifted = new Date(date - offset * 60 * 1000);
return shifted.toISOString().slice(0, -1);
}
OR, using Moment.js:
moment(yourDateObject).format("YYYY-MM-DD[T]HH:mm:ss.SSS")
Lastly, you will probably read advice from others about storing these as UTC. Don't listen. The advice "always use UTC" is shortsighted. Many scenarios require local time. Scheduling appointments is a primary use case for local time. However, if you need to act on that appointment, you'll use the current UTC time, and you'll also need some information about the time zone for the appointment so you can convert from UTC to the appointment's time zone. For example, if this is something like an in-person doctor's office appointment, then it's safe to assume the time zone of the doctor's office. But if it's an appointment for an online meeting, then you'll have to capture the user's time zone separately and apply it on the back end where appropriate.
The problem is with your current timezone.
What your application does is get current timezone (+3) in this case.
Now it got your timezone but it will convert to utc time. So what will happen, your current time will be -3 hours.
If you not adjust to summer and winter time then you can simply add 3 hours to the datetime. Otherwise you have to get the offset of your timezone and add that to the current datetime value.
Take care if you use this application in different timezones. For example You life in +3 and some else life in +2 timezone.

Converting moment UTC to Local date time

I put a UTC .NET/JSON date from .net on client side. When I run the following command:
moment(value.Planet.when).utc()
The returned date from webservice:
"/Date(1469271646000)/"
I get a date in the _d parameter showing the current accurate UTC date with GMT+0300 on right side.
I want to convert this time to local time on the user machine and what ever I do, I always get the time 3 hours back.
I do this:
moment(value.Planet.when).local().format('YYYY-MM-DD HH:mm:ss')
and I get the same date time as the UTC. I don't understand how can I get momentjs to show the UTC time relative to the local time. I checked that the momentjs object is indeed UTC.
I thought that if I pass the moment.utc() function the UTC date that I've got from the webservice (originally from the database), I can just run the local() function and I'll get the accurate hour relative to my area, but it didn't work.
You can use moment(date).format('YYYY-MM-DDTHH:mm:ss');
Eg:- if you date "/Date(1469271646000)/"
ip-> moment(1469271646000).format('YYYY-MM-DDTHH:mm:ss');
op-> "2016-07-23T16:30:46"
Do not use the _d property. It is for internal use only. See this answer, the user guide, or Maggie's blog post on the subject.
As far as you question of how to convert to local time, you don't actually need to convert at all. You're already parsing the input value in local mode, so you can just use it directly:
var m = moment("/Date(1469271646000)/"); // gives you a moment object in local mode.
var s = m.format(); // lets you format it as a string. Pass parameters if you like.
var d = m.toDate(); // gives you a Date object if you really need one
Try to avoid using Date objects unless they're required by some other controls or libraries you're using. Most operations can be done strictly on moment objects.

Having troubles with converting time in iso using java

I use the below code to format date time in iso format using java (I'm reducing 1 min from current time) and get the output as this "2016-03-17T11:38:21.xxxZ" < x represent some numbers> i want this to compare with the time which have mentioned in the DB.
Person who build that data insert query, he used javascript to get the time and format it in iso.
Date inside the DB is looks like this "2016-03-17T06:09:21.530Z" and its actual time is "11:39:21 GMT+0530 (India Standard Time)" which is similar to my current time but I'm comparing these two dates as string. and get 1min early data from DB.In that case i can't get an out put because as strings these two aren't match. can anybody recomand a solusion ?
I use OrientDB
Java Code
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar date = Calendar.getInstance();
long t = date.getTimeInMillis();
date.setTimeInMillis(t);
date.set(Calendar.MINUTE, date.get(Calendar.MINUTE) - 1);
String time1minEarly = df.format(date.getTime());
Using Calendar.set() and Calendar.get() does not modify the date in a way you intend:
This will modify the minutes field in your case. So subtracting "1" will reduce the minute but not give a viable date for cases where minute initially is zero.
You may just subtract a minutes of milliseconds from your "t" variable to get a true minute offset.
And for ease of use you might also consider following advise from #Prashant and using LocalDateTime class from joda library.
Thanks Everybody for your support.
I figure out How to do this. it's pretty easy. Both #rpy and #Prashant are correct. Calendar is not suitable for solve my issue. Also LocalDateTime too. but it did help me to figure out the correct way.
#rpy and #Prashant they both did miss one thing that the javascript time represent the UTC time. that's the issue. (it's 5.5 hours behind compared to my location) so, I figure out this below code. it did what i wanted to do.
It's pretty easy. all you have to do is provide your zone id.
(You can get Zone id using this code : go to the link - http://www.javadb.com/list-possible-timezones-or-zoneids-in-java/)
Also you can choose so many formats by changing "DateTimeFormatter" value.
ZoneId UTCzoneId = ZoneId.of("UTC");
ZonedDateTime time1minEarly = ZonedDateTime.now(UTCzoneId).minusMinutes(1);
String UTCtime1minerly = time1minEarly.format(DateTimeFormatter.ISO_INSTANT);
Out put is similar to this : "2016-03-17T10:39:21.530Z"
(- UTC time at that time : 2016-03-17T10:40:21.530Z)

parsing a UTC ISO date to a local time date in javascript/jquery

I have tried to search for the answer already, and although I find answers that are very similar, I don't think they are exactly what I am looking for. Please forgive me if this is already answered elsewhere.
I am trying to parse an ISO date in javascript so that I can compare it to the client system date and display information depending on if the ISO date is before or after the client system date.
This was fine until I needed to support IE8 and now I am stuck.
I have created a function because I have three different dates that I need to do this to.
for example, my ISO date is: 2015-12-22T11:59 in UTC time.
but once my date is parsed, the full date is 11:59 in local time, no matter which time zone i test, it's always 11.59 in THAT time zone.
I know that the function I have created currently doesn't do anything with timezone, this is where I am stuck. I don't know what to add to get my end date to change as a reflection of the timezone of the clients machine.
any help or advice would be greatly appreciated.
I am not able to use something like moments.js because I have an upload restriction.
Jquery is available though. or plain javascript.
<script>
function setSaleContent() {
//creating a new date object that takes the clients current system time. so we can compare it to the dates stored in our array
var currentDate = new Date();
console.log(currentDate + " this is the clients date ");
//These variables actually come from an external array object, but I'm putting them in here like this for this example.
var destinations = {
freedate: "2015-12-16T11:59",
courierdate: "2015-12-22T11:59",
nextdaydate: "2015-12-23T11:59",
}
//fetch all the ISO dates from the array.
var freeDateISO = destinations["freedate"];
var courierDateISO = destinations["courierdate"];
var nextdayDateISO = destinations["nextdaydate"];
//I am creating this reusable function to split up my ISO date for the sake of IE8.. and create it into a date format that can be compared against another date. I know that this isn't doing anything with my timezone and that is where my problem lies.
function parseDate(str) {
var parts = /^(\d{4}).(\d{2}).(\d{2}).(\d{2}):(\d{2})/.exec(str);
if (parts) {
return new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5]);
}
return new Date();
}
//I would like this date to change to reflect the time zone of the clients system time.
//currently returns the date at 11.59 regardless of timezone.
//If i was in GMT i would want it to say 11.59
//If i was in CT time I would like this to say 05.59
//If i was in Perth I would like this to say 19:59
var freeDate = parseDate(freeDateISO);
console.log(freeDate + " this is the converted date for IE")
}
window.onload = setSaleContent;
The simple solution is to append Z to the ISO date to indicate it is in UTC time, such as 2015-12-22T11:59Z.
When JavaScript parses that date as a string, it will then automatically convert the UTC date to the local time zone.
While this is simple enough with a parsing call in the form new Date(str);, it will not play nice with your parse call with numerical arguments targeting IE8 and other old browsers.
A polyfill for parsing ISO dates with timezone exists: Javascript JSON Date parse in IE7/IE8 returns NaN
This can replace your custom parseDate function after some modification to take an input string.
Alternatively, implement your own custom date manipulater to account for the local timezone using the .getTimezoneOffset() method on the newly created date, which gives the time zone offset in minutes, but you will have to come up with a method of utilising the offset such as adjusting hours and minutes, due to the limited methods of the JavaScript date object.

Categories