Solved my own problem. I wanted to convert seconds to HH:mm:ss using moment.js. I used the following code, which worked, but I didn't know why moment(0) was setting the time of day to 19 00
var yearZero = moment(0).subtract('hours',19); //beginning of time
var sTimecode = yearZero.add('seconds', secondsUntilEvent).format("HH:mm:ss");
From http://momentjs.com/docs/#/parsing/unix-offset/
moment(Number);
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).
Didn't see anything about starting at 7PM / 19 00 there
The problem was that I was outputting it without declaring UTC. The following change did the trick:
var sTimecode = moment(0).add('seconds', secondsUntilEvent).utc().format("HH:mm:ss");
Perhaps someone else encountered the same problem (or not). Good day!
Instead of doing such a complicated workaround, you can always use the moment constructor to read an integer, which is interpreted as the number of milliseconds from the unix epoch. This works fine for me:
var value = moment(18000 * 1000).format('HH:mm:ss'); // 5 Hours
document.getElementById('date').innerHTML = value;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<pre id="date"></pre>
Obviously, the time is displayed accordingly to your browser's timezone
Related
I am having a hard time to calculate the duration (difference in time) of two timestamps.
There is a timestamp I receive from the server in the following format:
start # => "2017-05-31 06:30:10 UTC"
(This is basically rubys DateTime.now.utc)
I want to see how many hours have passed since then until as of right now.
The calculation happens in the angularjs frontend only.
I tried the following:
var start = moment("2017-05-31 06:30:10 UTC", "YYYY-MM-DD HH:mm:ss Z").utc();
var now = moment.utc();
var duration = moment.duration(now.diff(start));
console.log(duration.asHours()); #=> 2 hours even though the point in time was just a couple of minutes ago.
Unfortunately this would always use my devices local time and produce a time that's a few hours off the actual time.
So my approach was to either convert all times to UTC and let momentjs handle all this.
What am I missing?
Since your input is UTC you can use moment.utc method.
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use moment.utc() instead of moment().
Here a live example:
var start = moment.utc("2017-05-31 06:30:10 UTC", "YYYY-MM-DD HH:mm:ss Z");
var now = moment.utc();
var duration = moment.duration(now.diff(start));
console.log(duration.asHours());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
In your code sample, you are parsing the input string as local date and then converting it to UTC (with utc() method).
See Local vs UTC vs Offset guide to get more info.
I need to display on the screen some date values but I'm receiving them in a format that I don't know. Does anybody know what format is this and how to convert them?
For example, I'm getting this:
/Date(1427982649000-0400)/
In the database is stored as
2015-04-02 09:50:49.000
I really don't know where to start looking at.
It's a unix timestamp in milliseconds, followed by a timezone (shift in hours differing from UTC).
So, it's UTC -4 hours, 1427982649 seconds after the 1st January of 1970.
Nice little tool for checking unix timestamps : http://www.unixtimestamp.com/index.php (don't forget to convert your milliseconds to seconds before posting them there)
/edit: To add some additional information - the "timezone shift" seems to be following RFC822 (and/or probably some other RFCs), that -0400 can be explained by the syntax "+/-HHMM" specified there, so to be exact it means -04 hours, 00 minutes.
The actual time and date gets converted into the milliseconds, and it follows the Unix time January 1st, 1970.
Because it is the date when the time for the Unix computer started.
But you can convert the milliseconds into the actual time by using some loops or conversions according to that time.
Does anybody know what format is this and how to convert them?
It seems that "/Date(1427982649000-0400)/" is a time value in milliseconds followed by an offset as ±HHmm. To convert that to a Date, use the time value adjusted by the offset.
Assuming the offset uses the typical sign convention, then a positive offset needs to be subtracted and negative offset added to get the correct UTC value, then something like the following should suit:
var s = '/Date(1427982649000-0400)/';
// Get the number parts
var b = s.match(/\d+/g);
// Get the sign of the offset
var sign = /-/.test(s)? -1 : +1;
// Adjust the time value by the offset converted to milliseconds
// and use to create a Date
var ms = +b[0] + sign * (b[1].slice(0,2)*3.6e6 + b[1].slice(-2)*6e4);
console.log(new Date(ms).toISOString()); // 2015-04-02T17:50:49.000Z
In your example, "2015-04-02 09:50:49.000" does not have a timezone, so it represents a different moment in time for each timezone with a different offset. If that is the actual value stored in the database, then I guess the missing timezone is UTC-0800. It is much better to store the values using UTC and to include the offset, then the host timezone is irrelevant.
Things are complicated here because ECMAScript timezone offsets are the opposite sign to the normal convention, i.e. positive for west of Greenwich and negative for east. If that convention is applied, then "/Date(1427982649000-0400)/" converts to 2015-04-02T09:50:49.000Z, which may be what you're after.
If that is the case, just change the sign in the line:
var sign = /-/.test(s)? -1 : +1;
to
var sign = /-/.test(s)? +1 : -1;
Is there a way to indicate only the date portion of a Date() object, without indicating the time?
e.g.
var d = Date();
d.setFullYear(2015, 0, 13);
d.toString();
"Tue Jan 13 2015 00:00:00 GMT-0500 (EST)" // Wrong - I didn't set a time!
"Tue Jan 13 2015 NULL GMT-0500 (EST)" // Expected Result
I want to be able to tell the difference between a user who only inputed the Date portion, vs one who explicitly inputed both a Date and a Time
Not really. A Javascript Date object always has a time. You can leave it at midnight and ignore it if you want, but it'll still be there. It's up to you how you interpret it.
If you want to be able to represent a null time, you could interpret midnight to mean that, though then you would have no way to represent times that actually are midnight. If you want to be able to have a null time and still represent every possible time you would need to have two variables.
You could have:
// Date with null time
var date = new Date(2015, 0, 13); // time component ignored
var time = null;
// Date with non-null time
var date = new Date(2015, 0, 13); // time component ignored
var time = new Date(1970, 0, 1, 9, 30); // date component ignored
Note in the second example the year, month and day in the time component are arbitrary and won't be used, but they still need to be there if you want to create a Date object.
JavaScript Date objects are internally defined using number of milliseconds since January 1, 1970 UTC. Therefore you are stuck with the time part.
Try this code
var date = new Date(2015, 0, 13);
console.log(date.valueOf());
You'll get this output
1421125200000
Here is the standard definition...
ECMAScript Language Spec See page 165
From ECMA standard:
A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number
is called a time value. A time value may also be NaN, indicating that the Date object does not represent a
specific instant of time.
Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds
are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values
can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to
measure times to millisecond precision for any instant that is within approximately 285,616 years, either
forward or backward, from 01 January, 1970 UTC.
The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000
days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives
a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0
Dates are objects. As such, you can add properties to them as needed:
var date_only = new Date("2015-03-04");
date_only.time_is_meaningful = false;
var date_with_time = new Date("2015-03-04T10:47");
date_with_time.time_is_meaningful = true;
This is simpler and cleaner than your millisecond hack, and more
convenient than having two separate variables. You could then, if you
wish, subclass Date with a custom toString that checks the
time_is_meaningful property and acts accordingly.
You cannot remove the time information from a Date.
If you want to have both informations independently, use a Date for the date and ignore the time (e.g. ensure it's always exactly midnight for instance), and use another field to hold the time (it could be a Date where you ignore the date but not the time, or it could be one input text with formatted time, or several input texts with hour, minute, etc).
The UI representation is up to you.
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
I was trying to convert date object into long format (may be in milliseconds format) as we do in java.
So to fulfill my need, after some trial and error, I found below way which works for me:
var date = new Date();
var longFormat = date*1; // dont know what it does internally
console.log(longFormat); // output was 1380625095292
To verify, I reverse it using new Date(longFormat); and it gave me correct output. In short I was able to fulfill my need some how, but I am still blank what multiplication does internally ? When I tried to multiply current date with digit 2, it gave me some date of year 2057 !! does anyone know, what exactly happening ?
The long format displays the number of ticks after 01.01.1970, so for now its about 43 years.
* operator forces argument to be cast to number, I suppose, Date object has such casting probably with getTime().
You double the number of milliseconds - you get 43 more years, hence the 2057 (or so) year.
What you are getting when you multiply, is ticks
Visit: How to convert JavaScript date object into ticks
Also, when you * 2 it, you get the double value of ticks, so the date is of future
var date = new Date()
var ticks = date.getTime()
ref: Javascript Date Ticks
getTime returns the number of milliseconds since January 1, 1970. So when you * 1 it, you might have got value of this milliseconds. When you * 2 it, those milliseconds are doubled, and you get date of 2057!!
Dates are internally stored as a timestamp, which is a long-object (more info on timestamps). This is why you can create Dates with new Date(long). If you try to multiply a Date with an integer, this is what happens:
var date = new Date();
var longFormat = date*1;
// date*1 => date.getTime() * 1
console.log(longFormat); // output is 1380.....
Javascript tries to find the easiest conversion from date to a format that can be multiplied with the factor 1, which is in this case the internal long format
Just use a date object methods.
Read the docs: JavaScript Date object
var miliseconds=yourDateObject.getMiliseconds();
If You want to get ticks:
var ticks = ((yourDateObject.getTime() * 10000) + 621355968000000000);
or
var ticks = someDate.getTime();
Javascript date objects are based on a UTC time value that is milliseconds since 1 January 1970. It just so happens that Java uses the same epoch but the time value is seconds.
To get the time value, the getTime method can be used, or a mathematic operation can be applied to the date object, e.g.
var d = new Date();
alert(d.getTime()); // shows time value
alert(+d); // shows time value
The Date constructor also accepts a time value as an argument to create a date object, so to copy a date object you can do:
var d2 = new Date(+d);
If you do:
var d3 = new Date(2 * d);
you are effectively creating a date that is (very roughly):
1970 + (2013 - 1970) * 2 = 2056
You could try the parsing functionality of the Date constructor, whose result you then can stringify:
>
new Date("04/06/13").toString()
"Sun Apr 06 1913 00:00:00 GMT+0200"
// or something
But the parsing is implementation-dependent, and there won't be many engines that interpret your odd DD/MM/YY format correctly. If you had used MM/DD/YYYY, it probably would be recognized everywhere.
Instead, you want to ensure how it is parsed, so have to do it yourself and feed the single parts into the constructor:
var parts = "04/06/13".split("/"),
date = new Date(+parts[2]+2000, parts[1]-1, +parts[0]);
console.log(date.toString()); // Tue Jun 04 2013 00:00:00 GMT+0200