get UTC timestamp from today's local time - javascript

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);

Related

comapre javascript toUTCString() with UTC date time

From Authentication API along with token i am getting its expiry date time which is in UTC
I am using npm jwt-decode package to extract the info
private setToken(value: string) {
this._token = value;
var decoded = jwt_decode(value);
this._expiry = new Date(decoded['expiry']);
}
To check if token expired i compare it with current UTC dat time
isTokenExpired() {
var currentUTC = new Date().toUTCString() as any;
var flag = this._expiry < (currentUTC as Date);
if (flag)
return true;
else
return false;
}
but new Date().toUTCString() gives strig instaed of date which always retuen false when compare with date object
I tried to convert it to date but after conversion it show date as per browser local time zone instead of actual utc date time
console.log('current UTC : '+ currentUTC);
console.log('expiry UTC : '+ this._expiry);
console.log('utc string to UTC Date : ' + this.createDateUTC(currentUTC));
console.log(new Date(Date.parse(currentUTC as string)));
console.log(this._expiry < (currentUTC as Date));
createDateUTC(dateUTC) {
return new Date(dateUTC + "Z");
}
output is as follow
current UTC : Fri, 02 Sep 2022 02:32:21 GMT
expiry UTC : Fri Sep 02 2022 03:32:08 GMT+0530 (India Standard Time)
utc string to UTC Date : Invalid Date
Fri Sep 02 2022 08:02:21 GMT+0530 (India Standard Time)
Current UTC is correct
expiry UTC is correct , Current UTC + 1 hours as expiry time returned from api
third one is converted to date which is invalid date , Ref : stack overflow Post by Killer
fourth one , tried to parse but it after parsing its local time. UTC time lost.
Any idea how to convert UTC string to date object without loosing its actual value, or any other approach to get current UTC date time
Update 1 :
After refresh
this._expiry = new Date(decoded['expiry'])
inside setTokn() method also lost UTC date time and convert it as per local time
Update 2:
Tried code by "HsuTingHuan" but got same result. Issue persist
I had met similar case before. Hope my solution can help you
I was used the javascript Date object's toISOString() function or JSON.stringnify()(Because the JSON object will always convert to ISO 8601 format)
And compare all of the datetime object by ISO 8601 format
example works on EDGE:
var currentUTC = new Date().toISOString();
console.log(currentUTC)
function createDateUTC(dateUTC) {
return new Date(dateUTC);
}
var currentUTCDateobj = createDateUTC(currentUTC)
console.log(currentUTCDateobj)
var expiry = new Date("2022-09-02 00:00:00")
console.log(expiry)
console.log(expiry < currentUTCDateobj);

How do I save date/time in some other timezone

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

How to only change the hour and seconds portion of a utc timestamp?

I've got a UTC timestamp in milliseconds.
It represents 16:00 on a certain day in GMT time.
timestamp: 1450281600000
I want to modify only the hours, minutes component portion of this value and return the new value.
For example 16:30 is 59400000 but it doesn't have the days and year.
How do I correctly change the utc stamp?
I'm programming in Javascript.
Throw your timestamp into a Date object, manipulate it with the date functions, and then use valueOf to return a timestamp again.
var d = new Date(1450281600000);
d.setHours(1);
d.setMinutes(30);
alert(d.valueOf()); // 1450247400000
You'd want to use standard Date object.
For example, to change 16:00 to 16:30 of that day, you'd do like this:
dt = new Date(1450281600000); // instatiates Date from timestamp
// Wed Dec 16 2015 17:00:00 GMT+0100 (CET) in my local representation
dt.getMinutes(); // will return 0
dt.setMinutes(30);
// dt now is represented as 1450283400000 timestamp...
dt.getTime(); // ...which you can see here.

Convert Javascript Date object to PST time zone

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());

Convert GMT epoch to CST

I am trying to convert a GMT time which is stored as epoch into CST.
Below is the current code I am running in java.
if (originalRFC.get("sysmodtime")!=null){
var sysmod = originalRFC.get("sysmodtime"); // Hold the sysmodtime value in a variable
logger.debug('Sysmodtime Before: ' + sysmod); // Output to log before before converstion to CST - (in GMT)
var format = new java.text.SimpleDateFormat("MMMM d, yyyy HH:mm:ss a z"); // Format the string will be in
var dateString = sysmod.toLocaleString(); // Convert the epoch to the string equivalent in CST
var parsedDate = format.parse(dateString); // Convert that CST String back to epoch
var sysmodConvert = parsedDate.getTime(); // Convert it to time and milliseconds
logger.debug('Sysmodtime After: ' + sysmodConvert); //Output to log after conversion to CST
genericRFC.setField("last-update-time",sysmodConvert);
}
See the below errors that are returned in the log, we can see the time before"1301382996000", and it breaks when I try to convert:
2011-05-02 14:25:49,926 [http-8080-1] sm702-adapter_convert script - Sysmodtime Before: 1301382996000
2011-05-02 14:25:49,941 [http-8080-1] sm702-adapter_convert script - Error while calling function convert
org.apache.bsf.BSFException: JavaScript Error: java.text.ParseException: Unparseable date: "[object JavaObject]"
Presuming by "epoch" you mean a UNIX timestamp (seconds since the UNIX epoch), this time format is timezone-agnostic. That is, your timestamp is not UTC, GMT, CST or any other timezone. It's just a number of seconds.
You apply timezones when you re-format the timestamp as something human-readable. In this case, just load it into a Date object, and your local timezone should be used.
For starters, toLocaleString() is Locale dependent and might be different than the format you have used (it is actually beyond your control).
Sencondly, if you know the CST time zone offset, you can always use getTime() add the offset and use setTime() to get this converted.
In Java world there is something like java.util.TimeZone that can give you right offset (use getOffset()) in milliseconds already.

Categories