I'm using the following code to get the current UTC time in the correct format, but the client has come back and asked that the timestamp now be in EST instead of UTC. I have searched Google and stackoverflow, but can't find an answer that works with my existing code.
var currentdate = new Date();
var datetime = currentdate.getFullYear() + ":"
+ ("0" + (currentdate.getUTCMonth()+1)).slice(-2) + ":"
+ ("0" + currentdate.getUTCDate()).slice(-2) + ":"
+ ("0" + currentdate.getUTCHours()).slice(-2) + ":"
+ ("0" + currentdate.getUTCMinutes()).slice(-2) + ":"
+ ("0" + currentdate.getUTCSeconds()).slice(-2);
What we are trying to do is set a consistent timestamp to EST regardless of where the browser is located in the world, hence the use of the UTC time originally.
Thanks!
A few things...
The term "EST" can be used for either Eastern Standard Time in North America, or Eastern Standard Time in Australia. Most time zone abbreviations are not unique, so you should be more specific.
EST also does not define a time zone in its entirety. It only defines part of the time zone that is used during the winter months. The other half is called Eastern Daylight Time, abbreviated EDT. Your client probably meant "Eastern Time", which would need to take both into account.
The typical way to define time zones is as an identifier from the IANA time zone database. You can read more about it in the timezone tag wiki. For example, if your client meant Eastern Time in the United States, then your time zone is "America/New_York".
JavaScript inherently doesn't know anything about time zones, other than it's own and UTC. (The link that bjb568 gave does not handle daylight saving time properly.) In order to work with them on the client, you will need to use one of the libraries I list here.
Your current code is a bit strange in terms of output. Usually colons are used for separating only the time, and you are using them for all parts. Anyway, it's not converting anything, it's just outputting UTC.
You might do well with a library like moment.js and it's moment-timezone add-on. For example:
moment().tz("America/New_York").format("YYYY-MM-DD HH:mm:ss")
The following answer (copied from this link on this site) worked very well for me. It easily and correctly converted the following Zulu time (which is same as UTC) "2014-10-09T20:30:54Z" to South African time.
var tmpDate = New Date("enter any valid Date format here")
The javascript Date() function will automatically convert it to your local time.
Example:
var tmpDate = new Date("Fri Jul 21 02:00:00 GMT 2012")
alert(tmpDate);
//Result: Fri Jul 20 22:00:00 EDT 2012
Below line will work:
console.log(moment().tz("America/New_York").format("YYYY-MM-DD HH:mm:ss"))
Related
toLocaleString() is deprecated but seems to lack replacement
I have a website where I store member post dates in this format: YYYY-MM-DD HH:MM:SS
The problem is that these dates are all stored with the timezone UTC and I want to convert these dates using JS to the users OS timezone. I know I could just ask users to input their timezone but I would like to try something new which require as little user interaction as possible. The goal of the site is to make a forum which is incredibly easy and straightforward to use.
I have almost gotten it to work the way I want but it currently only supports Chrome it seems like. This is not good enough since I plan on having a lot of users.
Since the timezone offset varies it is not good enough to only retrieve the current time offset which a lot of topics here seem to suggest. I want to accurately display for e.g. registration dates.
This is my current solution (timezone test only supports chrome as far as I can tell) it is also implemented on the whole website which is in beta.
https://ingsan.net/timezone/
Source code below
var d = new Date();
var tzName = d.toLocaleString('en', {timeZoneName:'short'}).split('').pop();
var cusid_ele = document.getElementsByClassName('timestamp');
for (var i = 0; i < cusid_ele.length; ++i) {
var timestamp = cusid_ele[i];
timestamp.innerHTML += " "+tzName;
t = new Date(timestamp.innerHTML);
usertime = t.toLocaleString()
timestamp.innerHTML = usertime;
}
I have used this site for years without asking but this time I seem to be unable to find a topic similar enough to mine.
The method I use which might be questionably is simply replacing objects inside the assigned class name. I plan to do other classes for other format outputs.
<p>Register date: <span class="timestamp">2016-01-31 20:12:55</span></p>
If you got a solution to this issue I would very much appreciate it. I am no professional and never went to any course but I have managed to make ingsan.net on my own. Help a humble student out ;)
If all you're doing is converting from UTC to the browser's local time zone, you do not need to actually try to figure out what time zone that is. Just be sure your input is clearly identified as UTC, and the default behavior of the Date object is to display values in the browser's local time zone.
var input = "2016-01-31 20:12:55";
var d = new Date(input + " UTC");
var s = d.toString();
The resulting string will vary by implementation and time zone, such as (a few examples):
"Sun Jan 31 2016 12:12:55 GMT-0800 (Pacific Standard Time)"
"Sun Jan 31 2016 15:12:55 GMT-0500 (Eastern Standard Time)"
"Mon Feb 01 2016 01:42:55 GMT+0530 (India Standard Time)"
"Mon Feb 01 2016 09:12:55 GMT+1300 (New Zealand Daylight Time)"
This will work in all browsers. The only problem is that you don't have control over the format of the output string. That's where toLocaleString can help, though as you pointed out - it's not necessarily implemented in all browsers. However, you seemed to think it was deprecated, and it is not. It's actually part of a newer specification (ECMA-402), which just is not widely implemented everywhere (yet).
You have other options though. You could build the output string yourself, like this:
var z = function(x) {return x < 10 ? '0' + x : x};
var s = d.getFullYear() + '-' + z(d.getMonth() + 1) + '-' + z(d.getDate()) + ' '
+ z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
Of course you could figure out how to adjust to 12 hour format, use different separators, different date-field ordering (YMD vs DMY vs MDY), etc.
Or, you could just use a library such as moment.js which is already equipped for that.
var input = "2016-01-31 20:12:55";
var m = moment.utc(input).local(); // parse as UTC, then switch to local mode
var s = m.format(); // use any of the format parameters you wish
I have to display a string on the web page in this format: 16:00 HH:mm
I'm using a moment object to represent a date/time and timezone.
var day = moment().tz('GMT');
day.hours(16).minutes(0).seconds(0).milliseconds(0);
So this is 16:00 in GMT time.
On my web page I want to change the time zone and then collect the hours and minutes.
If I make a new moment object
var day2 = moment().tz('PST); //this is 8 AM since gmt was 16
console.log(day2.get('hours'));
it is 16 not 8!
and try to get the hours and minutes they are in GMT not in PST.
How can I get it in PST? Do I have to keep wrapping it?
// initialize a new moment object to midnight UTC of the current UTC day
var m1 = moment.utc().startOf('day');
// set the time you desire, in UTC
m1.hours(16).minutes(0);
// clone the existing moment object to create a new one
var m2 = moment(m1); // OR var m2 = m1.clone(); (both do the same thing)
// set the time zone of the new object
m2.tz('America/Los_Angeles');
// format the output for display
console.log(m2.format('HH:mm'));
Working jsFiddle here.
If you can't get it to work, then you haven't correctly loaded moment, moment-timezone, and the required time zone data. For the data, you either need to call moment.tz.add with the zone data for the zones you care about, or you need to use one of the moment-timezone-with-data files available on the site.
In the fiddle, you can see the moment-files I'm loading by expanding the External Resources section.
PST can mean different things in different regions. In the moment-timezone docs, I see nothing referring to "PST" or similar abbreviations.
Perhaps try:
var day2 = moment().tz('PST');
// 16 with Error: Moment Timezone has no data for PST. See http://momentjs.com/timezone/docs/#/data-loading/.
var day2 = moment().tz('America/Los_Angeles');
// 15
I don't know about using moment.js, but it's fairly simple using POJS and the same algorithm should work. Just subtract 8 hours from the UTC time of a date object and return a formatted string based on the adjusted UTC time.
Assuming PST is "Pacific Standard Time", also known as "Pacific Time" (PT), and is UTC -8:00:
/* #param {Date} date - input date object
** #returns {string} - time as hh:mm:ss
**
** Subtract 8 hours from date UTC time and return a formatted times string
*/
function getPSTTime(date) {
var d = new Date(+date);
d.setUTCHours(d.getUTCHours() - 8);
return ('0' + d.getUTCHours()).slice(-2) + ':' +
('0' + d.getUTCMinutes()).slice(-2) + ':' +
('0' + d.getUTCSeconds()).slice(-2);
}
document.write('Current PST time: ' + getPSTTime(new Date));
There is moment-timezone which adds functionality to moment.js for IANA time zones. For PST you can use America/Los_Angeles, however it might also automatically adjust for daylight saving so you'll get PDT when that applies. If you want ignore daylight saving, use the above or find a location with the offset you need and use that.
I'm in the middle of writing a website, and I got this marvellous idea. I would have my contact page change depending on the time zone it was viewed from.
Examples:
When viewed in the local time-zone (GMT +1):
I can be reached between 08:30 and 17:30
When viewed in New York (GMT -5):
I can be reached between 03:30 and 12:30
In San Francisco (GMT -8):
I can be reached between 00:30 and 09:30
In Beijing (GMT +8):
I can be reached between 16:30 and 01:30
... You get the idea.
I'm not sure where I should start. I know of moment.js but I'm not sure if it's suitable for this purpose, 'specially considering the fact that I want this to be automatically determined by the user's current location.
I'm using Node.js with Express.js for the server, and jQuery on the client-side. Any help?
You can create Date object with UTC time and get local time from it.
// args are in UTC time
function toLocalTime(hours, minutes){
var d = new Date(Date.UTC(0, 0, 1, hours, minutes, 0));
return [d.getHours(), d.getMinutes()].map(function(x){
return ('0' + x).slice(-2);
}).join(':');
}
"I can be reached between " + toLocalTime(07, 30) + " and " + toLocalTime(16, 30)
I'm in EDT and my end user is in PDT. I'd like my WebApp to operate as if it's running in the end user's timezone (e.g. even if they travel it's to show the time back home). The timestamps coming from the Java server are formatted to include the end user's timezone e.g. "Mon Oct 27 06:57:00 PDT 2014", and I also have the end user TZ string e.g. "America/Vancouver" in a config file. I'm using native Date() and it's displaying the right time for the user, but I can't use it to compare times with times in the client. I'm looking to change to moment.js, but I can't figure out how to get it to do what I want. Basically, given the above timestamp, I want to be able to call m.hour() and get 6 back. I also want to be able to get the day of the year in end user time (both "now" and for a timestamp), and see how far back the last timestamp is from the current time, in minutes. Here is my failed attempt:
var d = "Mon Oct 27 06:57:00 PDT 2014";
var ds = d.split(/ /).slice(1).join(' '); // eat "Mon "
var m = moment.tz(ds, "MMM D HH:mm:ss Z YYYY", "America/Vancouver");
alert("" + m.hour()); // 23 ??? Want "6"!
var n = moment.tz("America/Vancouver");
var df = n.diff(m, 'minute');
alert(m.format() + "\n" + n.format() +
"\n" + df + " minutes ago");
Fiddle: http://jsfiddle.net/up628qbq/
Thanks!
Use a lower-case z in the format string instead of the upper-case Z. That will match the time time zone abbreviation characters.
Note that this won't actually interpret the abbreviation as a particular offset. This is primarily because abbreviations can be ambiguous. (There are 5 different meanings of "CST"). Because of this, some values during a DST fall-back transition may be interpreted incorrectly.
For example, in the Pacific time zone, there are two instances of 1:00 AM on November 2 2014. The first is in PDT (-7) , and second is in PST (-8). Even though you provided an abbreviation, moment won't use it to disambiguate. If you want to be certain of which instance you are working with, you would need a numeric time zone offset to be included and parsed with Z.
Also, you can use ddd for the weekday name instead of splitting and slicing.
Thank you Matt! I don't have enough reputation to "vote up", so I have made the changes you recommend (remove split and add ddd format, change Z to z) in the fiddle: http://jsfiddle.net/up628qbq/1/
I have an existing date time string in place
new Date('2014-08-01T00:00:00')
But instead of returning 2014-08-01, it returns as 2014-07-31 in the actually angularJS view.
I wonder is this date time string valid, if not, why its not valid.
Could the T be the reason that the string return a wrong date?
The console.log return a date of Thu Jul 31 2014 20:00:00 GMT-0400 (EDT)
Thank You
Lets call those -2 are toxic vote downs. They should really recall the days when they are struggling to understand the basic concepts that now apparant to them. Its a shame.
At present (Autumn 2014), JavaScript's date/time format diverges from ISO-8601 in a very important way: If there's no timezone indicator on the string, it assumes Z ("Zulu", GMT).
So
new Date('2014-08-01T00:00:00')
...is August 1st at midnight GMT. If you live east of GMT, that will be on the 31st in your local time.
However, this incompatibility with ISO-8601 is being fixed in ES6 and some implementations (including the latest V8 in Chrome) are already updating it. The ES6 spec changes the default to local time; check out ยง20.3.1.15 ("Date Time String Format", the section number may change) in the draft PDFs or this unofficial HTML version.
The displayed date uses the timezone of your browser/computer. This means that if you are in GMT-1 and you enter 2014-08-01T00:00:00, the actual date is 2014-08-01T00:00:00 - 1 hour = 2014-07-31T23:00:00
I have this date in startdate=2021-10-27T00:00:00-04:00,
d=new Date(data.StartDate) // outputTue Oct 26 2021 23:00:00 GMT-0500
But date is getting one day before'Tue Oct 26 2021 23:00:00 GMT-0500' in central timezone(below -6,-7,-8...).
Actually I used this it is working fine but for central timezone not working
var d = new Date(data.StartDate);
console.log(data.startDate);
$scope.txtStartDate = ("0" + (d.getMonth() + 1)).slice(-2) + "/" + ("0" + d.getDate()).slice(-2) + "/" + d.getFullYear();