Mailgun events API timestamp - javascript

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

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.

Date.now official format name

I read the documentation for the Date.now() method.
It's understood what it returns, and my question focus on, literally, the format name.
I have a REST call, where on of its properties is expirtyDate, and I wish to format to be as returned by the Date.now() method (i.e- the numbers of milliseconds passed from Jan 1970).
But how can I describe this format the my teammates? I can't tell them "use the Date.now() of JS". I prefer to ask them for "use time format"
So how should I call this format?
From the documentation you link to:
the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC
or
the milliseconds elapsed since the UNIX epoch
AKA UNIX time, POSIX time, and epoch time).

Converting UTC milliseconds to Central Time in javascript

We have a bunch of systems events that are stored in a database with a milliseconds timestamp in UTC. In order for me to get the JSON I need, I just need to send a request like this....
http://xxx.xxx.xxx/gimmeJson?starttime=MILLISECONDS&endtime=MILLISECONDS
So when an event happened at 11:00pm CST it has been converted to the UTC millisecond equivalent and stored.
I am having a big issue wrapping my head around milliseconds because I'm thinking about it like timezones.
I saw a SO question similar to this here: How do I convert UTC/ GMT datetime to CST in Javascript? (not local, CST always) and it was close but not quite there.
If timestamps are stored in UTC milliseconds, how can I query them for their Central time equivalent? By that I mean my boss wants a report of all events that happened in the central timezone but I have to query a database that has these timestamps stored as UTC milliseconds.
Ultimately I have to come up with ** some ** number to send on a URL for UTC MILLISECONDS that is the equivalent of say "September 24, 12:00:00 Central". What compounds this issue is that the web service is fairly new and has been shown to be a bit buggy so I need to make sure I have this right.
// construct a moment object with Central time input
var m = moment('2015-01-01 00:00:00').format('x');
// convert using the TZDB identifier for GMT
m.tz('Europe/London');
// format output however you desire
var s = m.format("x");
Can someone confirm I am on the right track?
Many, many thanks in advance.
There's no such thing as milliseconds timestamp in UTC or any other timezone. Millisecond timestamps are always from 1970-01-01T00:00:00.000Z; they are zone agnostic.
In order to get the timestamp for the zone you want, simple create a Date instance and use the Date.prototype.getTime method
var cstTime = new Date('2016-09-24T12:00:00-06:00');
console.log('CST in ISO 8601:', cstTime.toISOString());
console.log('CST timestamp:', cstTime.getTime());
var localTime = new Date();
console.log('Local time in ISO 8601:', localTime.toISOString());
console.log('Local timestamp:', localTime.getTime());

Convert epoch js with false time in device

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.

How do you account for time-zone offset when retriving an "All Day" event from Google Calendar API?

I have an Ajax call to retrieve information from a public Google Calendar:
$.ajax({
url: "https://www.google.com/calendar/feeds/{CalID}/public/full?start-min={StartTime}&start-max={endTime}&alt=json-in-script&callback=?";
dataType: 'json',
timeout: 3000,
success: function( data ) { ProcessData(data);},
});
Within function ProcessData(data) I have the following statement:
StartTime = new Date(data.feed.entry[i].gd$when[j].startTime);
which stores in StartTime a Date() object with the date a particular event starts. Google normally uses ISO 8601 time format: YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00) and this works just fine. However, for "All Day" events the format is only in the form: YYYY-MM-DD (eg 1997-07-16) (Which is allowed by W3 http://www.w3.org/TR/NOTE-datetime) and in this case new Date() will interpret this as GMT. This is, will correct that particular date to your local time zone even if the event was already created in your local time-zone. In my particular case, when retrieving an "All Day" event on, say, April 7th 2014 happening in my time zone would return a string as if it was 5 hours earlier
new Date("2014-04-07")
returns Sun Apr 06 2014 19:00:00 GMT-0500 (CDT) which is off by 5 hours. (See the following question for more details on date parsing)
Have you ever had to deal with this issue when using Google Calendar? And if so, how did you solve it? Should I be using a different method instead of new Date() that would actually account for the time zone?
Google's JSON response contains a parameter feed.timezone, which contains the Olson's Time Zone ID but I'd need a way to convert (hopefully another Ajax call or something like that) that ID into an actual offset. I found the following question in this forum but the problem with this is that the parameter this API needs is the actual city and not the time Zone ID making me then to somehow make the translation from time zone ID to a city to pass to the URL string.
Any help would be appreciated!
When you say ISO 8601 strings with an offset "work just fine", are you leaving parsing up to the Date constructor, or are you doing it yourself? Some browsers won't correctly parse an ISO string, and more won't correctly parse a string with an offset. There's an answer here that shows how to parse an ISO string with offset for all browsers.
In regard to how to deal with dates, that is an issue that only has a business logic answer. If it is interpreted as an ISO 8601 string, then in any timezone that is west of Greenwich (or more than an hour west during its daylight saving time), it will result in a date one day before. If you wish to treat it as a local date, you'll need to first test the string to see if it's just a date and if so, treat it as local, e.g.
if (/^\d{4}-\d{2}-\d{2}/.test(dateString) {
// treat as date
} else {
// treat as date and time
}
Parsing the string as a local date is pretty simple:
// Expect a date string in ISO 8601 format YYYY-MM-DD
// Date is created as a local date
function parseLocalDateTime(s) {
s = s.split(/\D+/g);
return new Date(s[0], --s[1], s[2]);
}

Categories