moment api method to calculate Today's time in milliseconds - javascript

var timeArr = moment().format('HH:mm').split(':');
var timeInMilliseconds = (timeArr[0] * 3600000) + (timeArr[1] * 60000);
This is my current solution. I'd rather use the moment api to calculate today's time (time since 12:00am today) in milliseconds.
My code returns today's time in milliseconds. I need to call another function in milliseconds. I can not use the epoch. I need today's time formated in milliseconds.
Examples:
9:00am = 3.24e+7 milliseconds
9:00pm = 6.84e+7 milliseconds.

You can try the following:
var moment = require("moment");
// Compute the time in milliseconds assuming it's 1AM now
moment("1:00","HH:mm")-moment("00:00","HH:mm")
// 3600000
// Compute the time in milliseconds assuming it's 9AM now
moment("9:00","HH:mm")-moment("00:00","HH:mm")
// 32400000
// Compute the time in milliseconds assuming it's 9PM now
moment("21:00","HH:mm")-moment("00:00","HH:mm")
// 75600000
// For current time
moment()-moment("00:00","HH:mm")

You can use the following functions:
moment() - this gives you the current moment ("now")
startOf('day') - this gives you the first moment of the day
diff - this calculates the difference between two moments
Putting it together:
moment().diff(moment().startOf('day'))
The default units are milliseconds, so you don't need to specify them.
This gives you the elapsed milliseconds since the start of the day. However, note that there are some time zones (Brazil, for example) where the DST spring-forward transition occurs right at the stroke of midnight - on such days, the clocks go from 23:59:59 to 01:00:00, so the first moment of the day might not be midnight! In that situation, values returned by the above function might appear to be off by an hour from what you expect. It is indeed returning time since the start of the day, just not time from "midnight".
To compensate for this possibility, you can do the following instead:
moment().utcOffset(0, true).diff(moment().utcOffset(0, true).startOf('day'))
The utcOffset(0, true) will flip to UTC mode while keeping the local time intact. This is a little more convoluted than the first example, but gets the job done because UTC never experiences DST transitions.

Related

Moment js - can't get time passed from the beginning of the day

I'm trying to get the time in seconds that passed since 00:00:00 of today. e.g at 13pm I want to get that 13*60*60*1000 seconds have passed.
I tried using moment().valueOf() but I get the unix epoch time although it states in other questions that it's supposed to retrieve what I'm looking for.
(I'm using moment js in react native for that matter)
moment() gives you the current time.
moment().startOf('day') gives you the start of the current day.
(moment() - moment().startOf('day')) will give you the current number of milliseconds since the start of the day.
Divide that by 1000 and you've got the number of seconds since the start of the day.
var seconds = (moment() - moment().startOf('day')) / 1000;
You want to get the current time, and subtract it by the time at the very start of the day.
const now = new moment()
const dayStart = new moment().format('YYYY MM DD')
const msSinceStart = now.diff(dayStart)

Time Zones in Json Date

I am sending Json data via a REST Service to my client. This client should use the data to Display it.
My client uses JavaScript.
I am converting the date in the following way:
var from = new Date(myJsonDate.match(/\d+/)[0] * 1);
The JSON looks like this:
...="From":"\/Date(1450134000000)\/" ...
My problem is that the dates are correct in Germany but are off by one day in Brazil (e.g. showing Sunday instead of Monday in Brazil).
Does this code use time zones and calculates this accordingly?
How could I turn this off?
I want that the date is displayed exactly how i have sent it.
The operations with dates in JavaScript have a time zone variation in which the client machine is configured.
Right opportunity had to fix a function that showed difference between dates and nobody knew because. When you instance a date, the return her appears as: “Thu Feb 14 2008 08:41:27 GMT-0300 (Official Hour of Brazil)”
Note that in date has the GMT (Greenwich Mean Time) that indicates in which time zone the date is configured.
I’ll show as avoid the difference of time caused by this in operations with date. To this we have create a function that convert the date always to the time zone that if wait.
var calculateTimeZone = function(date, offset) {
var miliseconds_with_utc = date.getTime() + (date.getTimezoneOffset() * 60000);
return new Date(miliseconds_with_utc + (3600000 * offset));
}
Note that in the line 3, we invoke the method getTime() that convert the local moment of date to a number represented by miliseconds since January 1st, 1970 (Unix Epoch). We get the current time zone that is set in browser by method geTimezoneOffset() of API the date in JavaScript and we multiply by miliseconds of time of a hour. We add then the two values.
Why a hour?
Why this is the time that represents each time zone. By default this method return this time zone in minutes, by this the convertion in hour is necessary.
For to arrive this number 60000 you have that remember that 1 second have 1000 miliseconds and which 1 minute have 60 seconds, then converting minutes for miliseconds we multiply 60*1000 = 60000.
This moment we have the UTC (Coordinated Universal Time) represented by variable “utc” by sum of local moment the time zone in miliseconds.
We need now get a date starting this UTC added with the time zone of destiny, how by example a date expressed in time zone +5 transforming in time zone of brazil (Hour of Brazilian).
Note that in line 5 we got an offset (Time Zone Representation) in hour and converting to miliseconds. Remember that here 1 second have 1000 miliseconds and which 1 hour have 3600 seconds, then convert hour in miliseconds should multiply 1000 * 3600 = 3600000.
We add this result with the value of variable “utc” and we got the moment to the time zone wanted. Thenceforth we create a new date with based in long appropriate and return this new date.
In this way we can maintain of integrity desired in application when we need expressed a date in right time zone.
Does this code use time zones and calculates this accordingly?
No. Passing a number to the Date constructor is interpreted as a time value, i.e. milliseconds since 1970-01-01T00:00:00Z. Regardless of the settings of the client, it will create a Date for exactly the same instant in time.
However, by default, Date.prototype.toString uses the host system settings to apply an offset to the displayed values as "local" time.
How could I turn this off?
Modify the script engine. It's part of the ECMAScript standard so any implementation that doesn't do it is non–compliant.
I want that the date is displayed exactly how i have sent it.
Either:
Send it as a plain string, not as a date
Also send the time zone offset of the source so you can apply it at the other end to keep the date the same.
ECMAScript offsets have an opposite sense to most standards, they're -ve for east and +ve for west, so to get a Date with local settings that has the same as the source system:
var d = new Date(timevalue);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() - sourceTimezoneOffset);
Where sourceTimezoneOffset is the offset of the source system in minutes, +ve for west and -ve for east.
Usually dates related to a specific time zone, so as pointed out, the date in one place might be different to the date in another place at the same instant in time.
If you are not doing any modifications in dates when sending it from server side, the date will be in the timezone where the server is hosted.
So, if your server is hosted in Germany, dates will be in Germany's timezone.
There would be 2 ways to solve this:
Send dates to client in user-timezone from server in the response.
Make adjustments in your client application to implement appropriate
date conversion.

javascript dates converted to bst time on android devices when using Firefox

I have a web application that runs on Chrome without any problems on a Android Device but when running it on Firefox it converts the "newvalue" to BST time zone instead of GMT Standard Time.
var now = new Date();
var start = new Date();
var newvalue = new Date(now - start);
The newvalue timezone output is GMT+0100(BST) but should actually be GMT+0000(GMT Standard Time)
Firefox is adding an an extra hour.
I have tried to convert to UTC and GMT but doesn't seem to work.
Any ideas?
OK so ... Ermmm ... I'm not clear on what you're doing with the line:
var newvalue = new Date(now - start);
Are you trying to time something?
Regardless, the first thing this line does is to subtract start from now, and give the difference between the 2 dates in milliseconds. Assuming this happens basically instantly, the result will be approximately (if not precisely) 0 milliseconds.
When you create a date and pass in a single parameter like this, you are asking for the date as it was, X milliseconds after epoch. Epoch is defined as Thursday Jan 1st 1970 (for reasons I won't go into). So by creating a new Date with a parameter of 0, you're just asking the browser to give you epoch.
Why Firefox decides to give you epoch in BST instead of GMT, I'll grant is actually pretty odd (since Jan 1st is clearly not in British Summer Time). But this fact is probably irrelevant, given that this is almost certainly NOT what you are trying to achieve here. If you're trying to time something, I'd suggest you probably just want to do:
var newvalue = start - now;
Where newvalue is now the difference in time. Note: I have swapped now and start around, since in your example start is defined after now, and hence this will give you the positive time difference.
EDIT IN RESPONSE TO COMMENT
To be clear, I'm suggesting that you DON'T create a new Date object with the result of the subtraction.
If you want to get the number of milliseconds between the two times using dates, just subtract them:
var start = new Date();
// do time consuming stuff
var end = new Date();
var difference = end - start; // NOT: var difference = new Date(end - start)
Resolved the issue by turning the two dates in to a UTC date and then finding the difference between the two dates using milliseconds.
This then works on Android.
Thanks for your assistance

Javascript Epoch Time In Days

I need the epoch time in days. I've seen posts on how to translate it to date but none in days. I'm pretty bad with epoch time...how could I get this?
I need the epoch time in days
I'll interpret that you want the number of days since the epoch. The epoch itself is day zero (or the start of day 1, however you want to view it).
At the heart of a javascript Date object is a number of milliseconds since 1970-01-01T00:00:00Z. So to get the number of days from then to now you simply get the current time value and divide it by the number of milliseconds in one day:
var now = new Date();
var fullDaysSinceEpoch = Math.floor(now/8.64e7);
For 2012-10-05 you should get 15618. Not sure if it allows for leap seconds and such, but it should be close enough (within a few seconds) if the system clock is accurate.
It is only when reading values of a Date object (such as getHours() and toString()) that the timezone offset is applied to give local times.

Getting current date in milliseconds (UTC) (NO use of strings)

Well, you might think that this question has already been asked, but I think it has not. The solutions I've read about all had this "jigsaw puzzle" technique (like getUTCMonth() + getUTCMinutes + ...).
But as I only want to compare the elapsed seconds between two UTC (!) dates, this does not apply.
As everybody knows, you can get the current (non-UTC) date by:
var d = new Date();
var t_millis = d.getTime();
But this is NOT what I want. I'd like to have the current system date in UTC and in milliseconds, so not mess about with strings at all. AFAIK the variable t_millis will contain the millisecond value of the current timestamp in GMT, not UTC.
(Since d is in GMT as well. Unless getTime() does a sort of implicit time zone conversion, i. e. adding the offset BEFORE giving out the milliseconds, but I've never read about that anywhere)
So is there really no other way than adding the offset to the time value?
I'm desperately missing a function like getUTCTimeMillis() known from other languages.
This is an old question but for the sake of the new visitors here is THE CORRECT ANSWER:
Date.now();
It returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC
The millisecond value of the time-of-day is going to be the same regardless of your time zone. That is, there are no time zones on planet Earth that differ from one another by a number of milliseconds greater than zero. (They may differ by an integer number of hours or even minutes, but not seconds or milliseconds.)
That said, the value you get back from getTime() is a UTC-relative timestamp. If two web browsers at widely different spots on the globe create a Date object at the same time, they'll both get the same value from .getTime() (assuming the clocks are synchronized, which is of course highly unlikely).
Here: 1338585185539 That's a timestamp I just got from my browser. I'm in Austin, TX, and now it's 4:13 in the afternoon (so that timestamp will be from slightly before that). Plug it into a Date instance on your machine and see what it says.
(edit — for posterity's sake, that timestamp is from 1 June 2012.)
how about:
var now = new Date();
var utc_now = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
console.log('UTC: ' + utc_now) // correct UTC time but wrong timezone!
console.log('UTC (in ms): ' + utc_now.getTime())
I have used this function to solve the problem.
function getUTCNow()
{
var now = new Date();
var time = now.getTime();
var offset = now.getTimezoneOffset();
offset = offset * 60000;
return time - offset;
}
The getTime function returns the number of milliseconds elapsed since
1 January 1970 00:00:00 in the client timezone.
getTimezoneOffset return offset in minutes between Client timezone and UTC.
offset = offset * 60000; this operation transform minutes in miliseconds.
subtracting the offset get the number of milliseconds elapsed since 1
January 1970 00:00:00 UTC.
To get the timestamp from a date in UTC, you need to take in consideration the timezone and daylight savings for that date. For example, a date in January or in July could mean 1 hour difference.
The option below does just that.
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
It can be used as in:
var date = new Date();
var timestamp = date.getUTCTime();

Categories

Resources