How to convert GMT time to user's Local time Javascript - javascript

I'm trying to convert a GMT time to the user's Local time.
the format of the time i'm getting from the server is : 2015-05-20 18:00:00 GMT
I just want to show hours and minutes like that : 20:00
I wanted to use this solution which seems pretty easy, but I don't know how to make my format same as this
var date = new Date('5/21/2015 18:52:48');
date.toString();

the format of the time i'm getting from the server is : 2015-05-20 18:00:00 GMT
If so, you can easily massage that into a format that ES5 and higher browsers are supposed to support, which would be 2015-05-20T18:00:00Z for your example:
var yourString = "2015-05-20 18:00:00";
var dt = new Date(yourString.replace(' ', 'T') + "Z");
var hours = dt.getHours(); // Will be local time
var minutes = dt.getMinutes(); // Will be local time
Then just format the hours and minutes values you get into your desired hh:mm string.
Note: The Z at the end of the string is important. Unfortunately, the ES5 specification has a significant error in it (they're fixing it in ES6) around what the engine should do if there is no timezone on the string being parsed. Some engines do what the spec says, others do what the spec should have said (and the ES6 spec will say), which unfortunately means that right now, you can't trust what browsers will do if there's no timezone on the string.

I just had to add " UTC "
var date = new Date('2015-05-20 15:00:00 UTC');
alert(date.getHours());
alert(date.getMinutes());

new Date() in browser returns date object in user's timezone(machine timezone).
Just you need to pass GMT date to Date function in ISO format. So it will treat it as gmt time.
var date = new Date('2015-05-21T18:52:48Z');
date.toString();//You will get here date string in local format
You can also use UTC as UTC and GMT are same.
Here is ex.
var date = new Date('2015-05-21 18:52:48UTC'); //You can use GMT instead UTC
date.toString();//You will get here date string in local format
First method is preferable as second method doesn't work on Internet Explorer

Related

Jquery countdown in UTC [duplicate]

Suppose a user of your website enters a date range.
2009-1-1 to 2009-1-3
You need to send this date to a server for some processing, but the server expects all dates and times to be in UTC.
Now suppose the user is in Alaska. Since they are in a timezone quite different from UTC, the date range needs to be converted to something like this:
2009-1-1T8:00:00 to 2009-1-4T7:59:59
Using the JavaScript Date object, how would you convert the first "localized" date range into something the server will understand?
Simple and stupid
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(),
date.getUTCDate(), date.getUTCHours(),
date.getUTCMinutes(), date.getUTCSeconds());
console.log(new Date(now_utc));
console.log(date.toISOString());
The toISOString() method returns a string in simplified extended ISO
format (ISO 8601), which is always 24 or 27 characters long
(YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ,
respectively). The timezone is always zero UTC offset, as denoted by
the suffix "Z".
Source: MDN web docs
The format you need is created with the .toISOString() method. For older browsers (ie8 and under), which don't natively support this method, the shim can be found here:
This will give you the ability to do what you need:
var isoDateString = new Date().toISOString();
console.log(isoDateString);
For Timezone work, moment.js and moment.js timezone are really invaluable tools...especially for navigating timezones between client and server javascript.
Here's my method:
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
The resulting utc object isn't really a UTC date, but a local date shifted to match the UTC time (see comments). However, in practice it does the job.
Update: This answer is a quick-and-dirty way to get the UTC date when calling utc.toString(), utc.toLocaleString(), etc. Though, there are better solutions, in particular nowadays with modern browsers, and I should work on an improved answer. Basically, now.toISOString() (IE 9+) is what you want to use.
Convert to ISO without changing date/time
var now = new Date(); // Fri Feb 20 2015 19:29:31 GMT+0530 (India Standard Time)
var isoDate = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
//OUTPUT : 2015-02-20T19:29:31.238Z
Convert to ISO with change in date/time(date/time will be changed)
isoDate = new Date(now).toISOString();
//OUTPUT : 2015-02-20T13:59:31.238Z
Fiddle link
Date.prototype.toUTCArray= function(){
var D= this;
return [D.getUTCFullYear(), D.getUTCMonth(), D.getUTCDate(), D.getUTCHours(),
D.getUTCMinutes(), D.getUTCSeconds()];
}
Date.prototype.toISO= function(){
var tem, A= this.toUTCArray(), i= 0;
A[1]+= 1;
while(i++<7){
tem= A[i];
if(tem<10) A[i]= '0'+tem;
}
return A.splice(0, 3).join('-')+'T'+A.join(':');
}
Another solution to convert to UTC and keep it as a date object:
(It works by removing the ' GMT' part from the end of the formatted string, then putting it back into the Date constructor)
const now = new Date();
const now_utc = new Date(now.toUTCString().slice(0, -4));
console.log(now_utc.toString()); // ignore the timezone
I needed to do this to interface with a datetime picker library. But in general it's a bad idea to work with dates this way.
Users generally want to work with datetimes in their local time, so you either update the server side code to parse datetime strings with offsets correctly, then convert to UTC (best option) or you convert to a UTC string client-side before sending to the server (like in Will Stern's answer)
Browsers may differ, and you should also remember to not trust any info generated by the client, that being said, the below statement works for me (Google Chrome v24 on Mac OS X 10.8.2)
var utcDate = new Date(new Date().getTime());
edit: "How is this different than just new Date()?" see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
If no arguments are provided, the constructor creates a JavaScript Date object for the current date and time according to system settings.
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. (note: Date.UTC() returns the number of millisecond since 1970-01-01 00:00:00 UTC)
Adding the 60000 * Date.getTimezoneOffset() as previous answers have stated is incorrect. First, you must think of all Dates/Times as already being UTC with a timezone modifier for display purposes.
Again, browsers may differ, however, Date.getTime() returns the number of milliseconds since 1970-01-01 UTC/GMT. If you create a new Date using this number as I do above, it will be UTC/GMT. However, if you display it by calling .toString() it will appear to be in your local timezone because .toString() uses your local timezone, not the timezone of the Date object it is called on.
I have also found that if you call .getTimezoneOffset() on a date, it will return your local timezone, not the timezone of the date object you called it on (I can't verify this to be standard however).
In my browser, adding 60000 * Date.getTimezoneOffset() creates a DateTime that is not UTC. However when displayed within my browser (ex: .toString() ), it displays a DateTime in my local timezone that would be correct UTC time if timezone info is ignored.
My solution keeps the date the same no matter what timezone is set on the client-side. Maybe someone will find it useful.
My use case:
I'm creating a todo app, where you set date of your task. This date should remain constant no matter what timezone you're in.
Example. You want to call your friend at 8 am on June 25th.
You create this task 5 days before (June 20th) while you're in China.
Then, on the same day, you fly to New York for a few days.
Then on June 25th, while you're still in New York, you wake up at 7:30 am (which means you should receive task notification in 30 mins (even tho it's 1:30 pm already in China where you were when creating the task)
So the task is ignoring the timezone. It means 'I want to do it at 8 am in whatever timezone I'll be in'.
What I do is let's say 'I assume you're always in London Timezone - UTC'.
What it means is - when the user picks some date in her/his Timezone - I convert this date to the same date in UTC. ie. You pick 8 am in China, but I convert it to 8 am in UTC.
Then - next time you open the app - I read the date saved in UTC and convert it to the same date in your current timezone - eg. I convert 8 am in UTC to 8 am in the New York timezone.
This solution means that the date can mean something else depending on where you are when setting it and where you're reading it, but it remains constant in a way that it 'feels' like you're always in the same timezone.
Let's write some code:
First - we have 2 main functions for converting from/to UTC ignoring timezone:
export function convertLocalDateToUTCIgnoringTimezone(date: Date) {
const timestamp = Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds(),
);
return new Date(timestamp);
}
export function convertUTCToLocalDateIgnoringTimezone(utcDate: Date) {
return new Date(
utcDate.getUTCFullYear(),
utcDate.getUTCMonth(),
utcDate.getUTCDate(),
utcDate.getUTCHours(),
utcDate.getUTCMinutes(),
utcDate.getUTCSeconds(),
utcDate.getUTCMilliseconds(),
);
}
Then, I save/read this date like:
function saveTaskDate(localDate: Date) {
// I convert your local calendar date so it looks like you've picked it being in UTC somewhere around London
const utcDate = convertLocalDateToUTCIgnoringTimezone(localDate);
api.saveTaskDate(utcDate);
}
function readTaskDate(taskUtcDate: Date) {
// I convert this UTC date to 'look in your local timezone' as if you were now in UTC somewhere around london
const localDateWithSameDayAsUTC = convertUTCToLocalDateIgnoringTimezone(taskUtcDate);
// this date will have the same calendar day as the one you've picked previously
// no matter where you were saving it and where you are now
}
var myDate = new Date(); // Set this to your date in whichever timezone.
var utcDate = myDate.toUTCString();
Are you trying to convert the date into a string like that?
I'd make a function to do that, and, though it's slightly controversial, add it to the Date prototype. If you're not comfortable with doing that, then you can put it as a standalone function, passing the date as a parameter.
Date.prototype.getISOString = function() {
var zone = '', temp = -this.getTimezoneOffset() / 60 * 100;
if (temp >= 0) zone += "+";
zone += (Math.abs(temp) < 100 ? "00" : (Math.abs(temp) < 1000 ? "0" : "")) + temp;
// "2009-6-4T14:7:32+10:00"
return this.getFullYear() // 2009
+ "-"
+ (this.getMonth() + 1) // 6
+ "-"
+ this.getDate() // 4
+ "T"
+ this.getHours() // 14
+ ":"
+ this.getMinutes() // 7
+ ":"
+ this.getSeconds() // 32
+ zone.substr(0, 3) // +10
+ ":"
+ String(temp).substr(-2) // 00
;
};
If you needed it in UTC time, just replace all the get* functions with getUTC*, eg: getUTCFullYear, getUTCMonth, getUTCHours... and then just add "+00:00" at the end instead of the user's timezone offset.
date = '2012-07-28'; stringdate = new Date(date).toISOString();
ought to work in most newer browsers. it returns 2012-07-28T00:00:00.000Z on Firefox 6.0
My recommendation when working with dates is to parse the date into individual fields from user input. You can use it as a full string, but you are playing with fire.
JavaScript can treat two equal dates in different formats differently.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Never do anything like:
new Date('date as text');
Once you have your date parsed into its individual fields from user input, create a date object. Once the date object is created convert it to UTC by adding the time zone offset. I can't stress how important it is to use the offset from the date object due to DST (that's another discussion however to show why).
var year = getFullYear('date as text');
var month = getMonth('date as text');
var dayOfMonth = getDate('date as text');
var date = new Date(year, month, dayOfMonth);
var offsetInMs = ((date.getTimezoneOffset() * 60) // Seconds
* 1000); // Milliseconds
var utcDate = new Date(date.getTime + offsetInMs);
Now you can pass the date to the server in UTC time. Again I would highly recommend against using any date strings. Either pass it to the server broken down to the lowest granularity you need e.g. year, month, day, minute or as a value like milliseconds from the unix epoch.
If you are dealing with dates a lot, it's worth using moment.js (http://momentjs.com). The method to convert to UTC would be:
moment(yourTime).utc()
You can use format to change your date to any format you want:
moment(yourTime).utc().format("YYYY-MM-DD")
There is offset options in moment as well but there is an additional complementary library for dealing with timezone (http://momentjs.com/timezone/). The time conversion would be as simple as this:
moment.tz(yourUTCTime, "America/New_York")
I've found the jQuery Globalization Plugin date parsing to work best. Other methods had cross-browser issues and stuff like date.js had not been updated in quite a while.
You also don't need a datePicker on the page. You can just call something similar to the example given in the docs:
$.parseDate('yy-mm-dd', '2007-01-26');
I just discovered that the 1.2.3 version of Steven Levithan's date.format.js does just what I want. It allows you to supply a format string for a JavaScript date and will convert from local time to UTC. Here's the code I'm using now:
// JavaScript dates don't like hyphens!
var rectifiedDateText = dateText.replace(/-/g, "/");
var d = new Date(rectifiedDateText);
// Using a predefined mask from date.format.js.
var convertedDate = dateFormat(d, 'isoUtcDateTime');
Using moment.js UTC method;
const moment = require('moment');
const utc = moment.utc(new Date(string));
This function works beautifully for me.
function ParseDateForSave(dateValue) {
// create a new date object
var newDate = new Date(parseInt(dateValue.substr(6)));
// return the UTC version of the date
return newDate.toISOString();
}
This method will give you : 2017-08-04T11:15:00.000+04:30 and you can ignore zone variable to simply get 2017-08-04T11:15:00.000.
function getLocalIsoDateTime(dtString) {
if(dtString == "")
return "";
var offset = new Date().getTimezoneOffset();
var localISOTime = (new Date(new Date(dtString) - offset * 60000 /*offset in milliseconds*/)).toISOString().slice(0,-1);
//Next two lines can be removed if zone isn't needed.
var absO = Math.abs(offset);
var zone = (offset < 0 ? "+" : "-") + ("00" + Math.floor(absO / 60)).slice(-2) + ":" + ("00" + (absO % 60)).slice(-2);
return localISOTime + zone;
}
If you need Date Object
Passing only date string Date assumes time to be 00:00 shifted by time zone:
new Date('2019-03-11')
Sun Mar 10 2019 18:00:00 GMT-0600 (Central Standard Time)
If you add current hours and minutes you get proper date:
new Date('2019-03-11 ' + new Date().getHours() + ':' + new Date().getMinutes())
Mon Mar 11 2019 04:36:00 GMT-0600 (Central Standard Time)
The getTimezoneOffset() method returns the time zone difference, in
minutes, from current locale (host system settings) to UTC.
Source: MDN web docs
This means that the offset is positive if the local timezone is behind UTC, and negative if it is ahead. For example, for time zone UTC+02:00, -120 will be returned.
let d = new Date();
console.log(d);
d.setTime(d.getTime() + (d.getTimezoneOffset() * 60000));
console.log(d);
NOTE: This will shift the date object time to UTC±00:00 and not convert its timezone so the date object timezone will still the same but the value will be in UTC±00:00.
This is what I have done in the past:
var utcDateString = new Date(new Date().toUTCString()).toISOString();
For other people whos goal is to get it as a "Date Object" and not as a string, and you only want to display the date/time without the TZ (probably hardcoded), what you can do is:
const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth();
const day = now.getUTCDate();
const hour = now.getUTCHours();
const tomorrowUTC= new Date();
tomorrowUTC.setDate(day + 1); // +1 because my logic is to get "tomorrow"
tomorrowUTC.setYear(year);
tomorrowUTC.setMonth(month);
tomorrowUTC.Hours(hour);
// then use the tomorrowUTC for to display/format it
// tomorrowUTC is a "Date" and not a string.
You can then do stuff like:
We will delete your account at ${format(tomorrowUTC, 'EEEE do MMMM hh:mmaaa')} UTC
(format is a date-fns function, you can use other lib if you want);
This is kinda "hacky" as this is still using your local timezone, but if you just wanna display the date and not the timezone, then this works.
If your date has the timezone on it you can use date-fns-tz:
import { zonedTimeToUtc } from 'date-fns-tz';
const dateBrazil = new Date() // I'm in Brazil, you should have or get the user timezone.
const dateUtc = zonedTimeToUtc(dateBrazil, 'America/Sao_Paulo')
Looking at your question its clear that you just want to send the date range to your backend for further post processing.
I am assuming you are conforming to the standard data guidelines which expect the data to be in a particular format. For example, I use ODATA which is a RESTfull API which expects date time objects to be in the format:-
YYYY-MM-DDT00:00:00.
That can be easily achieved via the snippet posted below(Please change the format as per your requirement).
var mydate;//assuming this is my date object which I want to expose
var UTCDateStr = mydate.getUTCFullYear() + "-" + mydate.getUTCMonth() + "-" + mydate.getUTCDate() + "T00:00:00";
If on the other hand, you are in my situation wherein you have received a date from your backend, and the browser converts that to your local date. You on the other hand are interested in the UTC date then you can perform the following:-
var mydate;//assuming this is my date object which I want to expose
var UTCDate = new Date(mydate);/*create a copy of your date object. Only needed if you for some reason need the original local date*/
UTCDate.setTime(UTCDate.getTime() + UTCDate.getTimezoneOffset() * 60 * 1000);
The code snippet above basically adds/subtracts the time added/subtracted by the browser based on the timezone.
For example if I am in EST(GMT-5) and my Service returns a date time object = Wed Aug 17 2016 00:00:00 GMT-0500
my browser automatically subtracts the timezone offset(5hrs) to get my local time. So if I try to fetch the time I get Wed Aug 16 2016 19:00:00 GMT-0500. This causes a lot of problems. There are a lot of libraries out there which will definitely make this easier but I wanted to share the pure JS approach.
For more info please have a look at: http://praveenlobo.com/blog/how-to-convert-javascript-local-date-to-utc-and-utc-to-local-date/ where in I got my inspiration.
Hope this helps!
var userdate = new Date("2009-1-1T8:00:00Z");
var timezone = userdate.getTimezoneOffset();
var serverdate = new Date(userdate.setMinutes(userdate.getMinutes()+parseInt(timezone)));
This will give you the proper UTC Date and Time.
It's because the getTimezoneOffset() will give you the timezone difference in minutes.
I recommend you that not to use toISOString() because the output will be in the string Hence in future you will not able to manipulate the date
Using moment package, you can easily convert a date string of UTC to a new Date object:
const moment = require('moment');
let b = new Date(moment.utc('2014-02-20 00:00:00.000000'));
let utc = b.toUTCString();
b.getTime();
This specially helps when your server do not support timezone and you want to store UTC date always in server and get it back as a new Date object. Above code worked for my requirement of similar issue that this thread is for. Sharing here so that it can help others. I do not see exactly above solution in any answer. Thanks.
I know this question is old, but was looking at this same issue, and one option would be to send date.valueOf() to the server instead. the valueOf() function of the javascript Date sends the number of milliseconds since midnight January 1, 1970 UTC.
valueOf()
You can use the following method to convert any js date to UTC:
let date = new Date(YOUR_DATE).toISOString()
// It would give the date in format "2020-06-16T12:30:00.000Z" where Part before T is date in YYYY-MM-DD format, part after T is time in format HH:MM:SS and Z stands for UTC - Zero hour offset
By far the best way I found to get the GMT time is first get your local date time. Then convert in to GMT String. Then use the string to build new time by removing the timezone.
let dtLocal = new Date()
let dt = new Date(dtLocal.toISOString().split('Z')[0])
Note: - it will create the new datetime in GMT. But it will be local date time as timezone will be attached to it.
Extension function:
if (!Date.prototype.toUTC){
Date.prototype.toUTC = function(){
var utcOffset = new Date().getTimezoneOffset();
var utcNow = new Date().addMinutes(utcOffset);
return utcNow;
};
}
Usage:
new Date().toUTC();

Send JavaScript date with milliseconds and timezone to Java webservice

I need to send my current date on UI as http request header to Java based webservice but facing issue as the javascript new Date method hides the millisecond data from date and forwards it to web service.
console.log(new Date())
LOGS - Thu Sep 07 2017 14:47:37 GMT+0530 (India Standard Time)
The millisecond information is not present. I however need that in a date type that Java webservice also considers as Date and not string. I read about momentjs format approach but that basically returns a string and not date.
What I need is like: Thu Sep 07 2017 15:10:46:955GMT+0530 (India Standard Time).
ECMAScript Dates are based on a time value that is milliseconds since 1970-01-01T00:00:00Z, so they are inherently UTC. Therefore the value returned by:
new Date().getTime();
// or more concisely
Date.now();
does not need a timezone and includes millisecond precision. You can also use toISOString which returns an ISO 8601 extended date with milliseconds, again using UTC, e.g. 2017-09-07T22:51:51.287Z.
The ISO format is very widely accepted, is conveniently human readable and is unambiguous.
However, if it's important to also convey the timezone of the source, you can use the timezone offset (which is returned in minutes to add to local time to get UTC) and format it to something more standard.
function getISOOffset(date) {
date = date || new Date();
function z(n){return ('0'+n).slice(-2)}
var offset = date.getTimezoneOffset();
// ECMScript offset sign is the reverse of ISO 8601
var sign = offset < 0? '+' : '-';
offset = Math.abs(offset);
return sign + z(offset/60 | 0) + ':' + z(offset % 60);
}
console.log('The host offset is UTC' + getISOOffset())
If you are ok with purely milliseconds you can use something like this:
Date.now(); // 1504785573971
This works on almost all modern browsers. It doesn't tell you the timezone of the user, but does give you a consistent number against which to compare (milliseconds since Midnight of January 1, 1970, GMT).
For the very specific timestamp you seek, you might need a library like moment.js - it's a pretty heavy solution, but gives you excellent control over formatting.
Moment.js Formatting Options
This will be a string as there is not truly agreed-upon formation for passing dates in JSON. It will require parsing logic in the Java. I don't have much experience on the Java side, but I believe the popular libraries like Jackson and GSON support this conversion.
If you are not using JSON to submit information to the server, normal form submissions are passed as a string and have to be parsed out on the server, anyway.

How to update the date to the current date for UTC -8

I want to display a UTC date using this JavaScriptcode on my webpage.
<script>
function myDate()
{
var now = new Date();
var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
var x = document.getElementById("demo");
x.innerHTML=d;
}
</script>
With this code I am getting UTC date displayed as a local string as follows: "Thu Jul 04 2013 00:00:00 GMT+0530 (India Standard Time)"
I do not want display the string with a local time offset (GMT+0530 (IST)), instead I want the time to appear as UTC string format
The date returned by different browser are of different format
to remove GMT OFFSET from date you can use replace
var d = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
d = d.toString().replace(/GMT.+/,"");
Firstly, the problem is that you are instantiating a local Date object by passing in the UTC year, month and day. This then creates a local Date with the values provided. by doing this you might be creating an incorrect date based on whether you want it to be UTC or local. IN your case, if you want var now as UTC, the way you are currently instantiating is incorrect as its in local time.
Anyway, dates can be tricky in in JavaScript, so I would consider using Moment.js for this
It's a fantastic library that provides all of the functions for manipulating and converting JavaScript dates that you could ever need.
For example with moment you can just do the following:
var now = moment(); // current date and time in local format
var nowAsUTC = now.utc(); // current local date and time converted to UTC
var alsoNowAsUTC = moment.utc() // same as the line above, but staring in UTC
console.log(nowUTC.format("DD/MM/YYYY, hh:mm:ss"))// prints a pretty UTC string
Hmmm.. Are you sure you want to display UTC-8? I will take a guess that you are really wanting to convert the time to US Pacific time zone. That is not always UTC-8. Sometimes it is UTC-8, and sometimes it is UTC-7.
If you're not actually in the US Pacific Time zone, the only way to do this reliably in JavaScript is with a library that implements the TZDB database. I list several of them here.
For example, using walltime-js library, you can do the following:
var date = new Date();
var pacific = WallTime.UTCToWallTime(date, "America/Los_Angeles");
var s = pacific.toDateString() + ' ' + pacific.toFormattedTime();
// output: "Fri Apr 26 2013 5:44 PM"
You can't just add or subtract a fixed number, because the target time zone may use a different offset depending on exactly what date you're talking about. This is primarily due to Daylight Saving Time, but also because time zones have changed over time.

JS get date in UTC time

I've created a date in JS like so:
var myDate = new Date('2013-01-01 00:00:00');
I assume JS reads this in as UTC time. But when I do something like myDate.getTime() the timestamp returned was something like 4AM GMT time.
Why is this? And how do I get the date as midnight in UTC time?
At least in Chrome, this works:
var myDate = new Date('2013-01-01 00:00:00 UTC');
It also works if you put GMT instead of UTC. But I don't know if this is cross-browser enough.
I live in India. Hence my timezone is the Indian Standard Time (IST) which is listed in the tz database as Asia/Kolkata. India is 5 hours 30 minutes ahead of GMT. Hence when I execute new Date("2013-01-01 00:00:00") the actual time at GMT is "2012-12-31 18:30:00".
I believe you live in America because you're in the EST timezone (GMT-04:00)? Am I right?
If you want to parse the time at GMT instead of your local timezone then do this:
new Date("2013-01-01T00:00:00+00:00");
Notice the capital T between the date and the time, and the +00:00 at the end. This is the format used to parse a given time in a specific timezone.
Given the date string "2013-01-01 00:00:00" you can convert it to the required format using the following function:
function formatDateString(string, timezone) {
return string.replace(" ", "T") + timezone;
}
Then you can create the date as follows:
new Date(formatDateString("2013-01-01 00:00:00", "+00:00"));
Another way to convert local time to GMT is as follows:
var timezone = new Date("1970-01-01 00:00:00"); // this is the start of unix time
Now that you have your own local timezone as a date object you can do:
new Date(new Date("2013-01-01 00:00:00") - timezone);
All the above methods produce the same date at GMT.
JS reads this with time zone that your computer uses.
You can try use myDate.toUTCString() for get date in UTC time.
If you want get timestamp use myDate.getTime()
Mine works simply by doing this
var datetime= new Date()
However the month is 1 low so you have to add one

How do you check whether a date is UTC in Javascript?

I've read this question:
How do you convert a JavaScript date to UTC?
and based on this I implemented this conversion in a dateTools module as follows:
[Update]
var dt, utcTime;
dt = new Date();
utcTime = new Date(Date.UTC(dt.getFullYear(),
dt.getMonth(),
dt.getDate(),
dt.getHours(),
dt.getMinutes(),
dt.getSeconds(),
dt.getMilliseconds()));
Now I'd like to write unit tests. My idea was to check whether the result is actually in UTC, but I don't know how.
All the toString, toUTCString and similar methods seem to be identical for the input (non UTC) and output (UTC) date.
Only the result of the getTime method differs.
Is there a way to check wheter a date is UTC in javascript? If not, is there a better idea to unit test this?
To give more context:
Only converting the it to a UTC string is not that helpful, because in the next step the date is sent to an Asp.net service and therefore converted to a string like:
'/Date([time])/'
with this code
var aspDate = '/Date(' + date.getTime() + ')/';
var aspDate = '/Date(' + date.getTime() + ')/';
This outputs the internal UNIX epoch value (UTC), which represents a timestamp. You can use the various toString methods to get a more verbose string representation of that timestamp:
.toString() uses the users timezone, result is something like "Fri Jan 25 2013 15:20:14 GMT+0100" (for me, at least, you might live in a different timezone)
.toUTCString() uses UTC, and the result will look like "Fri, 25 Jan 2013 14:20:15 GMT"
.toISOString() uses UTC, and formats the datestring according to ISO: "2013-01-25T14:20:20.061Z"
So how do we construct the time value that we want?
new Date() or Date.now() result in the current datetime. No matter what the user's timezone is, the timestamp is just the current moment.
new Date(year, month, …) uses the users timezone for constructing a timestamp from the single values. If you expect this to be the same across your user community, you are screwed. Even when not using time values but only dates it can lead to odd off-by-one errors.
You can use the setYear, setMonth, … and getYear, getMonth … methods to set/get single values on existing dates according to the users timezone. This is appropriate for input from/output to the user.
getTimezoneOffset() allows you to query the timezone that will be used for all these
new Date(timestring) and Date.parse cannot be trusted. If you feed them a string without explicit timezone denotation, the UA can act random. And if you want to feed a string with a proper format, you will be able to find a browser that does not accept it (old IEs, especially).
Date.UTC(year, month, …) allows you to construct a timestamp from values in the UTC timezone. This comes in handy for input/output of UTC strings.
Every get/set method has a UTC equivalent which you can also use for these things.
You can see now that your approach to get the user-timezone values and use them as if they were in UTC must be flawed. It means either dt or utcTime has the wrong value, although using the wrong output method may let it appear correct.
getTimezoneOffset
Syntax: object.getTimezoneOffset( ) This method
returns the difference in minutes between local time and Greenwich
Mean Time. This value is not a constant, as you might think, because
of the practice of using Daylight Saving Time.
i.e.
var myDate = new Date;
var myUTCDate = new Date(myDate - myDate.getTimezoneOffset() * 60000);
alert(myUTCDate);
note: 60000 is the number of milliseconds in a minute;

Categories

Resources