I need to save a Date: February 16th, 2017 5PM HST.
The database (Parse) only accepts JS Date. And, my system timezone is IST.
JS Date does not have the ability to save in a different timezone.
To overcome this, I save three variables. Date (Calculated, calculation explained below), Timezone Offset, Timezone
Date is converted using moment.tz(DateObject, Timezone).
But, calling the toDate() function, seems to change it back to IST.
On further examination, I found a _d key to the Moment object, which seems to have the converted datetime in IST.
But, I seem to cannot get it to work.
Any hints would be helpful.
What do you mean by "save in a different timezone"? Timezone is a presentation-layer concern. 01:00+00:00 and 02:00-01:00 are the same time, presented differently. The point in time is represented using a large integer (the timestamp), and this timestamp is the thing you should save.
When you load this timestamp and want to use it again: you can present it from the perspective of any zone you choose.
//-- parsing the user input...
// parse HST (Honolulu Standard Time) date-time
var inputTime = moment.tz("February 16th, 2017 5PM", "MMMM Do, YYYY hA", "Pacific/Honolulu");
// in case you want to double-check that it parsed correctly
var inputTimePrettyPrinted = inputTime.format(); // "2017-02-16T17:00:00-10:00"
// grab timestamp
var timestamp = +inputTime;
//-- presenting the stored timestamp in Indian Standard Time...
// install a timezone definition for Indian Standard Time
moment.tz.add("Asia/Calcutta|HMT BURT IST IST|-5R.k -6u -5u -6u|01232|-18LFR.k 1unn.k HB0 7zX0");
moment.tz.link("Asia/Calcutta|Asia/Kolkata");
var timePresentedInIndianTime = moment(timestamp).tz("Asia/Calcutta");
var indianTimePrettyPrinted = timePresentedInIndianTime.format(); // "2017-02-17T08:30:00+05:30"
Try something like this:
var UTC = new Date();
var UTC = UTC.getTime() // Get UTC Timestamp
var IST = new Date(date); // Clone UTC Timestamp
IST.setHours(IST.getHours() + 5); // set Hours to 5 hours later
IST.setMinutes(IST.getMinutes() + 30); // set Minutes to be 30 minutes later
var EST = new Date(date); // Clone date
EST.setHours(EST.getHours() - 4); // set EST to be 4 hour earlier
You can change according to your need.
You need to use moment tz to add to HST
var now = new Date();
moment.tz.add('HST|HST|a0|0|');
console.clear();
var converted = moment(now).tz("HST").format();
console.log(now);
console.log(converted);
Here is the jsfiddle link
Check console.log for the answer.
Fri Feb 17 2017 18:24:49 GMT+0530 (India Standard Time) //IST time
2017-02-17T02:54:49-10:00 // HST Time
Related
I got timestamp utc of new york from weather api, want to display current time in New York but it gives output something like this 'UTC Sun Dec 01 2019 05:00:00 GMT+0530 (India Standard Time)'.
See the code for reference
// Code 1
//I get timestamp_utc when console.log(data)
//timestamp_utc: "2019-12-01T05:00:00"
const utc = new Date(data.timestamp_utc)
console.log('UTC', utc)
// UTC Sun Dec 01 2019 05:00:00 GMT+0530 (India Standard Time)
// Code 2
// Another code for getting current time but, failed
var usaTime = new Date().toLocaleString("en-US", {timeZone: timezone}); // Here timezone is from props
console.log('USA time: '+usaTime) // USA time: 12/1/2019, 4:59:58 AM
I also have timezone data getting from weather API. My aim is to get current time based on timezone or utc timestamp. As you can see both my trials are unsuccessful. Expected output is 6:39 PM which is now current time in New York. Is there any good solution?
Let me start with your 'code 2'. This is the same as what you wrote but with the timezone filled in...
const timezone = "America/New_York";
const usaTime = new Date().toLocaleString( "en-US", { timeZone: timezone});
console.log( 'usaTime =', usaTime );
For me this works. I get the current time in NY formatted correctly for USA. I'm not sure why yours did not work but I wonder what you specified for the timezone string.
I also a bit puzzled by your 'Code 1'. The 'new Date()' that you created is being converted to a string and then printed by your console.log statement, but this should result in a ISO 8601 string and you seem to be getting a locale string (the date format).
Though the example string you gave is in ISO 8601 format, it is not explicitly UTC because it does not end with a Z, nor does it end with a time zone offset such as +00:00. Thus when you parse it with the Date constructor, it is interpreted as local time. You can fix this by adding the Z yourself (assuming the timestamp_utc field is consistently a string in that format):
// timestamp_utc: "2019-12-01T05:00:00"
const utc = new Date(data.timestamp_utc + 'Z'); // adding the Z forces parsing as UTC
Now you have a Date object. However, if you just pass it to console.log, the output you see is implementation dependent. You will either see the local time in the same format you'd get by calling toString, or you will see the UTC time in the same format you'd get by calling toISOString.
To get the time in a different time zone, now you can call toLocaleString and pass the timeZone option. This assumes that the time zone is a valid IANA time zone identifier, and that the environment where the code is running fully supports the time zone features of the ECMAScript Internationalization Specification (ECMA-402). This is indeed the case with most modern browsers, but you will not get correct output in older browsers such as Internet Explorer.
const usEasternTime = utc.toLocaleString("en-US", {timeZone: 'America/New_York'});
Lastly from your variable name usaTime, I think perhaps you might be under the assumption that the US has a single time zone, but it does not. You will need to pass the correct time zone identifier. See the list on Wikipedia.
Define the time zones of origin ($ sourceDate) and destination (to convert).
$sourceTimeZone = 'utc';
$targetTimeZone = 'America/Bogota';
Separate the components of the date of origin that is in the format ‘m / d / y h: m: s’.
list($month, $day, $year, $hours, $minutes, $seconds) = sscanf($sourceDate, "%d/%d/%d %d:%d:%f");
Build the DateTime object indicating the date and time zone in which it is located.
$datetime = new DateTime("{$year}-{$month}-{$day} {$hours}:{$minutes}:{$seconds}",
new DateTimeZone($sourceTimeZone));
Modify the time zone of the DateTime to the destination time zone.
$datetime -> setTimezone(new DateTimeZone($targetTimeZone));
Get the components of the new date with the modified time zone.
list($month2, $day2, $year2, $hours2, $minutes2, $seconds2) = sscanf($datetime -> format(‘m/d/Y H:i:s’), “%d/%d/%d %d:%d:%f”);
Show the dates.
echo "En {$sourceTimeZone}: {$day}/{$month}/{$year} {$hours}:{$minutes}:{$seconds}<br/>";
echo "En {$targetTimeZone}: {$day2}/{$month2}/{$year2} {$hours2}:{$minutes2}:{$seconds2}<br/>";
PD: For JavaScript this can help you Convert time to different timezone with jQuery
I have a rest api which gives me current date and previous month of current date, It has output like following:
{
fromDate:2018-03-22T00:00:00+04:30
toDate:2018-04-22T00:00:00+04:30
}
If I consume these two dates in JavaScript like below, I get different results:
new Date("2018-03-22T00:00:00+04:30")
console output: Wed Mar 21 2018 23:00:00 GMT+0330 (Iran Standard Time)
new Date("2018-04-22T00:00:00+04:30")
console output: Sun Apr 22 2018 00:00:00 GMT+0430 (Iran Daylight Time)
And on the c# side, I use this code to get dates from server:
var toDate = DateTime.Now.Date;
DateTime fromDate = toDate.AddMonths(-1);
how can I overcome this issue of not having different dates?
Due to the start of daylight saving time in Iran on 2018-03-22, as the clock approached 00:00:00, it was advanced by an hour to 01:00:00. If one observed the clock carefully during this time, one would see it advance as follows:
...
2018-03-21 23:59:58
2018-03-21 23:59:59
2018-03-22 01:00:00
2018-03-21 01:00:01
...
In other words, the values 00:00:00 through 00:59:59 on that day did not exist in the local time zone.
Since you are providing such a non-existent value in your fromDate, and your local computer's time zone is set for Iran, then JavaScript is converting it to a valid point in time, as follows:
2018-03-22T00:00:00+04:30 source input value
2018-03-21T19:30:00+00:00 converted to UTC
2018-03-21T23:00:00+03:30 converted to a valid local time
If you were looking to get the correct start of day for that day, your fromDate would have to be 2018-03-22T01:00:00+04:30.
To calculate that correctly on the server side in C#, you'll need to work with the TimeZoneInfo API. Consider the following helper method:
static DateTimeOffset GetStartOfDay(DateTime dt, TimeZoneInfo tz)
{
// Work in the time zone provided
if (dt.Kind != DateTimeKind.Unspecified)
{
dt = TimeZoneInfo.ConvertTime(dt, tz);
}
// Start with assuming midnight
var d = dt.Date;
// Check for the time being invalid and handle if so
if (tz.IsInvalidTime(d))
{
// the gap is *usually* 1hr, but not always, so calculate it
var gap = tz.GetUtcOffset(dt.AddDays(1)) - tz.GetUtcOffset(dt.AddDays(-1));
// advance forward by the amount of the gap
d = d.Add(gap);
}
// Also check for the time being ambiguous, such as in a fall-back transition.
// We want the *first* occurrence, which will have a *larger* offset
var offset = tz.IsAmbiguousTime(d)
? tz.GetAmbiguousTimeOffsets(d).OrderByDescending(x => x).First()
: tz.GetUtcOffset(d);
// Now we know when the date starts precisely
return new DateTimeOffset(d, offset);
}
With that declared, now you can easily obtain accurate values for your API:
var tz = TimeZoneInfo.FindSystemTimeZoneById("Iran Standard Time");
var date = new DateTime(2014, 3, 22); // or DateTime.UtcNow for the current date
DateTimeOffset fromDate = GetStartOfDay(date, tz);
DateTimeOffset toDate = GetStartOfDay(fromDate.AddDays(1).Date, tz);
Of course this assumes that Iran is the correct time zone you want to emit from your API. If you are serving a wider audience, then you may need to adjust the time zone accordingly.
Let's assume I know this time (hh:mm:ss) without date but I know it is today:
12:34:56
And I know the time is in CST timezone (UTC +0800). I need to get timestamp from the time.
Let's assume current UTC time is 2014/08/25 17:10:00 and CST is 2014/08/26 01:10:00 (UTC +0800) so it means in CST is already the next day. Therefore I can't use something like this:
var d = new Date().toJSON().slice(0,10);
// "d" returns "2014-08-25" in local time -> this is bad
I need to convert this:
1:10 (CST) --> to 2014/08/25 17:10 (UTC) or its timestamp 1408986600
How can I get full date-time or timestamp when I know the time and timezone only?
You can always manipulate the properties of a Date object directly:
var date = new Date();
date.setHours(5);
date.setMinutes(12);
date.setSeconds(10);
console.log(date.toUTCString());
I think I found the easy way using moment-timezone.js:
// hh:mm:ss in CST timezone
var cst_time = '1:10:00';
// get today's date in CST timezone
var cst_today = moment.tz("Asia/Shanghai").format("YYYY-MM-DD");
// convert date and time from CST to UTC and format it
var timestamp = moment(cst_today + " " + cst_time + " +0800").utc().format("YYYY/MM/DD HH:mm:ss");
// returns "2014/08/25 17:10:00" and it is correct
console.log(timestamp);
I have the following input and i can change the source of this data
Input
var strDate = "/Date(1391402871117+0100)/";
I can convert it to a date using eval, but i really dont want to eval
var DateResult1 = eval ("new Date(1391402871117+0100)");
console.log(DateResult1); // Date {Mon Feb 03 2014 05:47:51 GMT+0100 (Romance Standard Time)}
I did try this, sadly do not work:
// Remove /Date( )/
strDate = strDate.replace(/[^\d+]/g,'');
var DateResult3 = new Date(strDate);
console.log(DateResult3); //Date {Invalid Date}
When i write result of strDate i manual with out " it work.
var DateResult2 = new Date(1391402871117+0100);
console.log(DateResult2); // Date {Mon Feb 03 2014 05:47:51 GMT+0100 (Romance Standard Time)}
How can convert the input data into a date with out using eval or any library?
You are very likely not getting a correct result out of this code:
var DateResult2 = new Date(1391402871117+0100);
The problem is the addition: 1391402871117+0100. 0100 is an octal constant, equal to 64 in decimal, which would add 64 milliseconds to the 1391402871117 timestamp. It seems likely to be indended as a time zone instead, but the Date constructor does not support time zones — only UTC and the local time zone of the browser.
Since UNIX timestamps are actually absolute (they are always in UTC), using just the timestamp would result in a Date instance referencing the correct instant in time, but possibly at another time zone. You can disregard the +0100 part, by converting the "1391402871117+0100" into an integer using parseInt:
strDate = strDate.replace(/[^\d+]/g,'');
var DateResult2 = new Date(parseInt(strDate));
If you can change the data source, as you say, why not do this?
Have your data source generate something like this, to add the timezone offset to the timestamp:
// convert timezone offset hours into seconds and add them to the timestamp
return (unixTimestamp + (timezoneOffsetHours * 3600));
Then you can do something like this in your JS:
// Math.floor works faster than parseInt to convert a string to integer :)
var timestamp = Math.floor(result of above timestamp generation);
var DateResult = new Date(timestamp);
The reason:
new Date() can't handle timezones specified in this way (or at all as far as I can Google)
try by parsing string to int:
var strDate = "/Date(1391402871117+0100)/";
strDate = strDate.replace(/[^\d+]/g, '');
var DateResult3 = new Date(parseInt(strDate.split('+')[0]) + parseInt(strDate.split('+')[1]));
console.log(DateResult3);
Here is Demo
I need to pick a future date from calender, suppose the date I am selecting is 10/14/2014, now what I want is to send the date with the time to server, so that at server end it always reaches as 6am time in PST timezone and the format of date should be UTC.
What I am doing is
targetDate = new Date($("#calendar").val());
targetDate = targetDate.toUTCString();
targetDate = targetDate.addHours(14);
My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST
The problem I am facing is that it is not letting me to add 14 hours since the object has already been converted to string.
addHours is the custom function I am having to add the hours in given time.
If I write
targetDate = new Date($("#calendar").val());
targetDate = targetDate.addHours(14);
targetDate = targetDate.toUTCString();
then it works good but in this case problem is time will always be different when the request is coming from different timezones.
Any help is appreciated.
This worked for me:
var myDate = new Date(1633071599000)
var pstDate = myDate.toLocaleString("en-US", {
timeZone: "America/Los_Angeles"
})
console.log(pstDate)
Which outputs "9/30/2021, 11:59:59 PM"
You said:
My understanding is that PST timezone is -8:00 so I have added 14 hours to the UTC time so that time becomes 6:00am PST
Uh - no. That will put you on the following day. If you wanted to stay in PST, you would subtract 8 hours from the UTC time. -8:00 means that it is 8 hours behind UTC.
However, the Pacific Time zone isn't just fixed at PST. It alternates between PST (-8) and PDT (-7) for daylight saving time. In order to determine the correct offset, you need to use a library that implements the TZDB database. Refer to this duplicate answer here.
The only way to do it without a fancy library is to actually be in the pacific time zone. JavaScript will convert UTC dates to the local time zone for display, and it will use the correct offset. But it only knows about the local time zone. If Pacific Time is not your local time zone, then you must use a library.
Suggest you look at DateJS http://code.google.com/p/datejs/ or http://www.datejs.com/. Handles PDT for you.
Here is an alternative for you:
Use: Date.UTC(year, month, day, hours, minutes, seconds, ms)
Example:
For 1 Jan 2013 6AM PST
var date = new Date(Date.UTC(2013, 0, 1, 14, 0, 0))
console.log(date.toUTCString());
Prints: "Tue, 01 Jan 2013 14:00:00 GMT"
var date = new Date();
var utcDate = new Date(date.toUTCString());
utcDate.setHours(utcDate.getHours()-8);
var usDate = new Date(utcDate);
console.log(usDate);
document.getElementById('tmp_button-48523').addEventListener('click', function() {
let d = new Date();
let localTime = d.getTime();
let localOffset = d.getTimezoneOffset() * 60000;
let utc = localTime + localOffset;
let target_offset = -7;//PST from UTC 7 hours behind right now, will need to fix for daylight
let los_angles = utc+(3600000*target_offset);
nd = new Date(los_angles);
let current_day = nd.getDay();
let hours = nd.getHours();
let mins = nd.getMinutes();
alert("los_angles time is " + nd.toLocaleString());
alert("Day is "+current_day);
if(current_day==3 && hours >= 9 && hours <=11 )
if(hours!=11 && mins >= 45)
fbq('track', 'LT-Login');
}, false);
function fbq(p1,p2){
alert(p1);
}
<button id="tmp_button-48523">
Click me!
</button>
Here is the code that created to track fb pixel on Wednesdays between 9:45am PST and 11:00am PST
Mostly comment:
I need to pick a future date from calender, suppose the date I am
selecting is 10/14/2014,
Since there isn't a 14th month, I suppose you mean 14 October, 2014. Since this is an international forum, better to use an unambiguous format.
… and the format of date should be UTC
UTC is not a format, it's a standard time.
I think you are confused. If you want say 2014-10-14T06:00:00-08:00 in UTC, then the equivalent is 2014-10-14T14:00:00Z.
You are using the toUTCString method, but it is implementation dependent, so you'll get different results in different browsers. You probably want the toISOString method, but it's ES5 and not implemented in all browsers.
You need to provide some examples of how you want times to be converted, otherwise you may as well just get the date in ISO8601 format and append "T14:00:00Z" to it.
I think the question asks how to convert UTC to PST time (as indicated on the title). I'm making assumption that the local time is in pacific time (i.e. the server or local web browser etc)
if that's the case, in order to convert UTC time to local PST just do this
// Create date object from datetime (Assume this is the UTC /GMT) time
var date = new Date('Tue, 21 Apr 2020 09:20:30 GMT');
// Covert to local PST datetime, AGAIN this only works if the server/browser is in PST
date.toString();
I believe you can simply add 14 hours before converting to UTC.
Or you can create a new Date object out of the UTC string:
var date = new Date();
date = date.addHours(14);
var dateUTC = new Date(date.toUTCString());