Convert epoch js with false time in device - javascript

My local sensor-device is confiugured with localtime:"11.01.1970
09:35:39","utctimestamp":894939.
I can not set a ntp-client in the device.
I receive timestamp values in ms unit.
How can i convert it to the actual time with Javascript ?
new Date(ms) gives 1970 year values
And how i convert timestamps like 2015-07-09 00:00:00 to ms epoch values ?

You can do this by using a javascript plugin called moment.js
They have a very nicely maintained documentation.
Basically you can get the current time in javascript like:
new Date().getTime();
And this value can be converted to different formats using moment.js as per their documentation.

Related

convert date based on timezone user is in

I have a date I want to convert based on their timezone.
For example, I want to set it in EST time (America/New_York)
2019-04-24 12:00:00
and if the user comes across the site from America/Los_Angeles, it will appear:
2019-04-24 09:00:00
I need to be able to return the hour, so in that example: 9.
I tried using https://github.com/iansinnott/jstz to determine their timezone and https://moment.github.io/luxon in hopes of handling the conversion w/o any luck.
I was testing by changing the timezone on my computer w/o any luck.
It sounds like you're asking to convert from a specific time zone to the user's local time zone (whatever it may be). You do not need time zone detection for that, but at present you do need a library. (Answers that suggest using toLocaleString with a time zone parameter are incorrect, as that function converts to a specific time zone, but cannot go the other direction.)
Since you mentioned Luxon, I'll provide a Luxon specific answer:
luxon.DateTime.fromFormat('2019-04-24 12:00:00', // the input string
'yyyy-MM-dd HH:mm:ss', // the format of the input string
{ zone: 'America/New_York'}) // the time zone of the input
.toLocal() // convert to the user's local time
.toFormat('yyyy-MM-dd HH:mm:ss') // return a string in the same format
//=> "2019-04-24 09:00:00"
This capability is also provided by other libraries, such as date-fns-timezone, js-Joda, or Moment-Timezone, but it is not yet something built in to JavaScript.
Converting date based on the time can be done like this. reference convert date to another time zone example snippet is under.
var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/New_York"});
usaTime = new Date(usaTime);
console.log('USA time: '+usaTime.toLocaleString())
var usaTime = new Date().toLocaleString("en-US", {timeZone: "America/Los_Angeles"});
usaTime = new Date(usaTime);
console.log('USA time: '+usaTime.toLocaleString())
You could keep a list of timzeone identifiers and a list of their corresponding +/- number of hours with respect to your local time (which is returned by your time function).
Once you have a user's time zone, and you have extracted the current hour from the local timestamp simply look up the timezone in your list and use it's index to access the second list to find how many hours to add or subtract from the users time.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
// toLocaleString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleString());
// → "12/11/2012, 7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles
Or you can use getYear, getMonth, getDate, getHours, getMinutes, getSeconds to format your own representation of the date. These methods all return values according to the user's local timezone.
I think the question may need more clarification - my first impression was you refer to a date-time that you already have and serve from the server. Doesn't this problem boil down to the Date object being "user-timezone-aware"? or not? But it is (some methods are, to be exact)
Your date/time is 2019-04-24 12:00:00 EDT (i assume P.M.)
This means the Unix timestamp of this in milliseconds is 1556121600000
(i assume daylight is on for April so not pure EST but EDT and an offset of UTC-4:00)
When you call
console.log(new Date(1556121600000).getHours())
doesn't this return 9 as you suggest, for Javascript executed on a browser from America/Los_Angeles with PDT timezone?
As suggested at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours :
The getHours() method returns the hour for the specified date,
according to local time.

Mailgun events API timestamp

I'm making calls to the Mailgun events API but I'm confused by the timestamp format. Timestamps show as "timestamp": 1542251497.6072 or the longer format 1542358648.178141.
I can't find any reference to it in the documentation except their claim to follow "RFC822" specification.
How can I parse/convert these timestamps into JavaScript Date objects (GMT preferably)?
Since you already are using moment simply use the unix method:
moment.unix(1542251497.6072).format() // "2018-11-14T19:11:37-08:00"
moment.unix(1542358648.178141).format() // "2018-11-16T00:57:28-08:00"
Which:
Similar to new Date(Number), you can create a moment by passing an
integer value representing the number of milliseconds since the Unix
Epoch (Jan 1 1970 12AM UTC).

constructing a date object along with time zone

I want to construct a Date object along with dynamically selected timezone. I am currently in IST time zone. I want to eliminate the usage of Date.parse() as it does not behave as expected at times.
let's assume tzOffset to be +05:30 for now. It could be any other timezone based on what users want. new Date(epochDate).toISOString(); converts the date to UTC timezone. How do I get the date in toISOString() format but also get it in the desired time zone
const tsConstruct = `${year}-${month}-${date}T${hour}:${min}:00${tzOffset}`;
const epochDate = Date.parse(tsConstruct);
scheduledTs = new Date(epochDate).toISOString();
JavaScript's Date does not store timezone info. It just stores the number of milliseconds from UNIX EPOCH. Then, depending if you use the UTC methods or not, it returns the date and time in UTC or the local time.
You should have to change the date and time, based on the timezone indicated, to UTC or local time, and then store it in a Date object. But, of course, to show the stored time in another timezone different to the local one or UTC, you must do the conversions yourself, so, as #RuChengChong suggested, use a helper library like momentjs.

Converting UTC to local time doesn't work in javascript

My datetimes are stored in the DB as UTC. When they are sent to the client I want to convert them to local time.
Javascript receives a given datetime as a string that looks like this:
2016-09-29T19:13:40
If I run new Date('2016-09-29T19:13:40') on the string I get this output:
Thu Sep 29 2016 19:13:40 GMT-0400 (Eastern Daylight Time)
While the -0400 offset is present, it's not changing the time. Since UTC offsets aren't displayed to the user, it just looks like the timestamp is off by 4 hours.
Conversely if I do this:
new Date('2016-09-29T19:13:40').toISOString();
The output is:
2016-09-29T23:13:40.000Z
As you can see it actually adjusts the hours by 4 and eliminates the offset.
How come when I feed javascript a UTC datetime to convert to local all it does is add an offset, but when I feed it what it thinks is a local datetime it and ask it to convert to UTC it actually adjusts the time?
How can I get it to adjust a UTC datetime to local the way it adjusts local to UTC?
EDIT
Here's a fiddle: https://jsfiddle.net/qjmfLu67/1/
I'm getting different behavior between IE11 and Chrome. IE11 doesn't convert UTC to local. Chrome does convert UTC to local and if it recognizes a date as UTC, when you run toISOString on it, it doesn't adjust anything.
Working with date is not easy, especially if you do TZ conversions. I'd suggest to use momentjs (http://momentjs.com/docs/) for it, like I do.
// create a utc-zone moment
var x = moment.utc('2016-09-29T19:13:40')
x.format()
// output is "2016-09-29T19:13:40Z"
// adjust offset for the initial moment x by the local offset we get from moment created against local tz
x.utcOffset(moment().utcOffset());
x.format()
// output is "2016-09-29T22:13:40+03:00"
Looks like for IE11, you'll have to pass the date string in full javascript format for it to work properly.
new Date("Thu Sep 29 2015 19:13 GMT")
new Date('2016-09-29T19:13:40')
This is missing milliseconds and "Z" which are needed for a correct conversion from UTC to Local.
new Date('2016-09-29T19:13:40.000Z') should give you the correct time relative to your machine.

Is it Possible in javascript to restrict date to specific Timezone [duplicate]

I know I can get the local timezone offset via new Date().getTimeZoneOffset(). But where did Javascript get that information? Is there a way I can set it, so that all future Date objects have the offset I want? I tried searching the DOM in Firebug, but couldn't find anything.
What I am trying to accomplish is converting epoch times to readable format, but it needs to be in US/Central, no matter what the browser's OS setting. Because I am using US/Central, it's not a fixed difference from GMT. So instead of a bunch of super nasty conversion steps, why can't I just tell Javascript that I'm actually in US/Central?
Currently, Moment-Timezone enables us to set the "browser's" default timezone by using moment.tz.setDefault().
You'll have to use moment() instead of Date(), but this is still a nice upgrade over the weird JS Date object.
I know I can get the local timezone offset via new Date().getTimeZoneOffset(). But where did Javascript get that information?
An implementation of ECMAScript is expected to determine the local time zone adjustment.
Is there a way I can set it, so that all future Date objects have the offset I want?
No.
So instead of a bunch of super nasty conversion steps, why can't I just tell Javascript that I'm actually in US/Central?
Have you considered using a library?
I realize this is an old post, but momentJS is a powerful javascript library to manipulate date/time objects
Output format
If you are concerned about the output format, you always need to format you Date object prior to outputting it if you need it in a local timezone (e.g. using Intl) or you a library like dayjs or moment.
Create a new Date object from a date with a non-UTC timezone
You can set an offset in pure JS: new Date('2022-10-29T12:50:00.000+02:00') will contain 2022-10-29T10:50:00.000Z. You just have to always specify the timezone offset in /^[+-][0-2]\d:[0-5]\d$/ format.
console.log(new Date('2022-10-29T12:50:00.000+02:00').toISOString())
// Output
// 2022-10-29T10:50:00.000Z
Get timezone offset string from timezone offset number
Now, if you want to get an offset in that format from (new Date()).getTimezoneOffset() (e.g. -120), you need to
const tzOffsetNumber = (new Date()).getTimezoneOffset()
const tzOffsetString = `${tzOffsetNumber > 0 ? '+' : '-'}${Math.floor(Math.abs(tzOffsetNumber) / 60).toString().padStart(2, '0')}:${(Math.abs(tzOffsetNumber) % 60).toString().padStart(2, '0')}`
Get timezone offset string from IANA timezone
// Note: We need to specify a date in order to also consider DST settings.
const date = new Date()
const ianaTimezone = 'Europe/Bratislava'
const tzOffsetString = new Intl.DateTimeFormat('en', {timeZone: ianaTimezone, timeZoneName: 'longOffset'}).format(date).match(/[\d+:-]+$/)?.[0]

Categories