I have the following code that makes use of moment.js:
var Now = moment();
var UTC = moment().utc();
if (moment().isBefore(UTC)){
$("#was").html("Time difference : " + Now.from(UTC)).fadeIn('fast');
} else {
$("#was").html("Time difference : " + UTC.fromNow()).fadeIn('fast');
}
Result is always: "A few seconds ago". Can you tell me what I am doing wrong?
Although Now and UTC will display differently, they are the same "moment in time". To understand this you have to grasp how moment.js works internally. Here is some info from the official moment.js documentation (emphasis mine):
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().
So the difference is all in parsing and displaying. Internally, moment objects have the same timestamp. A little test to demonstrate this is to append (and run) the followin after your code:
console.log(Now.valueOf());
console.log(UTC.valueOf());
console.log(Now.valueOf() - UTC.valueOf()); // will be "a few secods" at most ;)
Update: If your intention was to create a moment of, say, 5 hours ago, then:
var hours_ago = 5;
var earlier = moment().subtract('hours', hours_ago); // 5 hours ago
var earlier_yet = moment().subtract({'days': 2, 'hours': 3}) // 2 days, 3 hours ago
Related
Im trying to convert duration in seconds to human friendly output using moment js and combination of duration and format.
Im getting the duration in seconds and then formatting it like so:
const value = 337650
const duration = (durationSeconds) => {
const duration = moment.duration(durationSeconds, 'seconds')
return moment.utc(duration.asMilliseconds()).format('D [days] HH:mm:ss')
}
console.log(`Duration: ${duration(value)}`)
outputs
"Duration: 4 days 21:47:30"
JSBin here
The problem I have is that it seems wrong. Online services like https://www.tools4noobs.com/online_tools/seconds_to_hh_mm_ss/ shows one day less.
Im not sure what library/algorithm these services are using and if they are showing the correct time elapsed or moment js.
Any ideas greatly appreciated!
You seem to be converting the duration into an epoch time, then formatting it, which will be wrong.
Take a look at this Moment issue for details about duration formatting. https://github.com/moment/moment/issues/1048
Simple formatting can be done using the humanize method:
let value = 337650
let duration = moment.duration(value, 'seconds')
duration = duration.humanize()
console.log(duration)
"4 days"
Fore more sophisticated formatting you may want to dive into: https://github.com/jsmreese/moment-duration-format.
try something simple:
var x = 337650%86400;
var days = (337650 - x)/86400;
var y = x%3600;
var hours= (x-y)/3600;
var sec = y%60;
var mins=(y-sec)/60;
alert(days + ' days ' + hours+':'+mins+':'+sec)
You can use the moment-duration-format plugin to format durations, the previous approach (creating a new absolute date from a duration) is not going to work. When you add 337650 seconds to the Unix Epoch start, you get January 4, 1970, 21:47:30, which is why you're seeing the day as 4.
As a further example of how this will go badly wrong, imagine we need to format a duration of, say, 2700000 seconds. This will give us an output of "1 days 06:00:00". Why? Because it's equivalent to February 1 1970, 06:00. (The real result will be 31 days, 06:00:00).
I don't think we can blame the authors of moment.js (they've done an amazing job), it's just not using the format function on moment.js as it is supposed to be used.
By using the format function from moment-duration-format, we're formatting as a duration rather than as an absolute time and we get the right result!
momentDurationFormatSetup(moment);
const value = 337650
const duration = (durationSeconds) => {
const duration = moment.duration(durationSeconds, 'seconds')
return duration.format('D [days] HH:mm:ss');
}
console.log(`Duration: ${duration(value)}`)
document.getElementById('output').innerHTML = `Duration: ${duration(value)}`;
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
<div id="output">
</div>
JSFiddle: https://jsfiddle.net/t07ez8o4/9/
I'm trying to get from a time formatted Cell (hh:mm:ss) the hour value, the values can be bigger 24:00:00 for example 20000:00:00 should give 20000:
Table:
if your read the Value of E1:
var total = sheet.getRange("E1").getValue();
Logger.log(total);
The result is:
Sat Apr 12 07:09:21 GMT+00:09 1902
Now I've tried to convert it to a Date object and get the Unix time stamp of it:
var date = new Date(total);
var milsec = date.getTime();
Logger.log(Utilities.formatString("%11.6f",milsec));
var hours = milsec / 1000 / 60 / 60;
Logger.log(hours)
1374127872020.000000
381702.1866722222
The question is how to get the correct value of 20000 ?
Expanding on what Serge did, I wrote some functions that should be a bit easier to read and take into account timezone differences between the spreadsheet and the script.
function getValueAsSeconds(range) {
var value = range.getValue();
// Get the date value in the spreadsheet's timezone.
var spreadsheetTimezone = range.getSheet().getParent().getSpreadsheetTimeZone();
var dateString = Utilities.formatDate(value, spreadsheetTimezone,
'EEE, d MMM yyyy HH:mm:ss');
var date = new Date(dateString);
// Initialize the date of the epoch.
var epoch = new Date('Dec 30, 1899 00:00:00');
// Calculate the number of milliseconds between the epoch and the value.
var diff = date.getTime() - epoch.getTime();
// Convert the milliseconds to seconds and return.
return Math.round(diff / 1000);
}
function getValueAsMinutes(range) {
return getValueAsSeconds(range) / 60;
}
function getValueAsHours(range) {
return getValueAsMinutes(range) / 60;
}
You can use these functions like so:
var range = SpreadsheetApp.getActiveSheet().getRange('A1');
Logger.log(getValueAsHours(range));
Needless to say, this is a lot of work to get the number of hours from a range. Please star Issue 402 which is a feature request to have the ability to get the literal string value from a cell.
There are two new functions getDisplayValue() and getDisplayValues() that returns the datetime or anything exactly the way it looks to you on a Spreadsheet. Check out the documentation here
The value you see (Sat Apr 12 07:09:21 GMT+00:09 1902) is the equivalent date in Javascript standard time that is 20000 hours later than ref date.
you should simply remove the spreadsheet reference value from your result to get what you want.
This code does the trick :
function getHours(){
var sh = SpreadsheetApp.getActiveSpreadsheet();
var cellValue = sh.getRange('E1').getValue();
var eqDate = new Date(cellValue);// this is the date object corresponding to your cell value in JS standard
Logger.log('Cell Date in JS format '+eqDate)
Logger.log('ref date in JS '+new Date(0,0,0,0,0,0));
var testOnZero = eqDate.getTime();Logger.log('Use this with a cell value = 0 to check the value to use in the next line of code '+testOnZero);
var hours = (eqDate.getTime()+ 2.2091616E12 )/3600000 ; // getTime retrieves the value in milliseconds, 2.2091616E12 is the difference between javascript ref and spreadsheet ref.
Logger.log('Value in hours with offset correction : '+hours); // show result in hours (obtained by dividing by 3600000)
}
note : this code gets only hours , if your going to have minutes and/or seconds then it should be developped to handle that too... let us know if you need it.
EDIT : a word of explanation...
Spreadsheets use a reference date of 12/30/1899 while Javascript is using 01/01/1970, that means there is a difference of 25568 days between both references. All this assuming we use the same time zone in both systems. When we convert a date value in a spreadsheet to a javascript date object the GAS engine automatically adds the difference to keep consistency between dates.
In this case we don't want to know the real date of something but rather an absolute hours value, ie a "duration", so we need to remove the 25568 day offset. This is done using the getTime() method that returns milliseconds counted from the JS reference date, the only thing we have to know is the value in milliseconds of the spreadsheet reference date and substract this value from the actual date object. Then a bit of maths to get hours instead of milliseconds and we're done.
I know this seems a bit complicated and I'm not sure my attempt to explain will really clarify the question but it's always worth trying isn't it ?
Anyway the result is what we needed as long as (as stated in the comments) one adjust the offset value according to the time zone settings of the spreadsheet. It would of course be possible to let the script handle that automatically but it would have make the script more complex, not sure it's really necessary.
For simple spreadsheets you may be able to change your spreadsheet timezone to GMT without daylight saving and use this short conversion function:
function durationToSeconds(value) {
var timezoneName = SpreadsheetApp.getActive().getSpreadsheetTimeZone();
if (timezoneName != "Etc/GMT") {
throw new Error("Timezone must be GMT to handle time durations, found " + timezoneName);
}
return (Number(value) + 2209161600000) / 1000;
}
Eric Koleda's answer is in many ways more general. I wrote this while trying to understand how it handles the corner cases with the spreadsheet timezone, browser timezone and the timezone changes in 1900 in Alaska and Stockholm.
Make a cell somewhere with a duration value of "00:00:00". This cell will be used as a reference. Could be a hidden cell, or a cell in a different sheet with config values. E.g. as below:
then write a function with two parameters - 1) value you want to process, and 2) reference value of "00:00:00". E.g.:
function gethours(val, ref) {
let dv = new Date(val)
let dr = new Date(ref)
return (dv.getTime() - dr.getTime())/(1000*60*60)
}
Since whatever Sheets are doing with the Duration type is exactly the same for both, we can now convert them to Dates and subtract, which gives correct value. In the code example above I used .getTime() which gives number of milliseconds since Jan 1, 1970, ... .
If we tried to compute what is exactly happening to the value, and make corrections, code gets too complicated.
One caveat: if the number of hours is very large say 200,000:00:00 there is substantial fractional value showing up since days/years are not exactly 24hrs/365days (? speculating here). Specifically, 200000:00:00 gives 200,000.16 as a result.
I'm using d3 v3 to parse some intraday data that has the following format:
time,value
09:00,1
09:05,2
09:10,3
...
So I set up a parsing variable like so:
var parseTime = d3.time.format("%H:%M").parse;
And I map the data within the scope of the csv call:
d3.csv("my_data.csv", function(error, rawData) {
var data = rawData.map(function(d) {
return {y_value: +d.value, date: parseTime(d.time)}
});
console.log(data)
}
In the console, I get something strange. Instead of only the hour, I get the full-fledged date, day of the week, month, even time zone.
data->
array[79]
0:Object->
date: Mon Jan 01 1900 09:00:00 GMT+0000
y_value: 1
Do dates need to be this complete? I suppose that could explain why I wound up with monday Jan. 1st, seems like a default of sorts. However, according to d3 time documentation, "%H:%M" is used for hours and minutes. And I could have sworn I did that much correct.
I know something is not quite right because my line graph is throwing the error:
error: <path> attribute d: expected number "MNaN"
My best guess is that the date is over-specified and the axis() is expecting an hour format.
My Question is: Why isn't my data being parsed as hour only? Should I change this from the parsing end? If that's not an option, can I have the x domain read a portion of the date (the hour and minute portion)?
Update: Here is a minimal block for further illustration of my plight.
When you say...
why isn't my data being parsed as hour only?
... it becomes evident that there is a basic misunderstanding here. Let's clarify it.
What is a date?
Simply put, a date is a moment in time. It can be now, or two months ago, or the day my son was born, or next Christmas, or the moment Socrates drank the hemlock. It does'n matter. What is important to understand is that all those dates have a century, a decade, a year, a month, a day, an hour, a minute, a second, a millisecond etc... (of course, those names are conventions that can be changed).
Therefore, it makes little sense having a date with just the hour, or just the hour and the minute.
Parsing and formating
When you parse a string, you create a date object. As we explained above, that date object corresponds to a moment in time, and it will have year, month, hour, timezone etc... If the string itself lacks some information, as year for instance, it will default to some value.
Look at this demo, we will parse a string into a date object, using the correct specifier:
var string = "09:00";
var parser = d3.timeParse("%H:%M");
var date = parser(string);
console.log("The date object is: " + date);
<script src="https://d3js.org/d3.v4.min.js"></script>
As you can see, we have a date object now. By the way, you can see that it defaults to a given year (1900), a given month (January), and so on...
However, in your chart, you don't need to show the entire object, that is, all the information regarding that moment in time. You can show just hour and minute, for instance. We will format that date.
Have a look:
var string = "09:00";
var parser = d3.timeParse("%H:%M");
var format = d3.timeFormat("%H:%M");
var date = parser(string);
console.log("The date object is: " + date);
console.log("The formatted date is: " + format(date));
<script src="https://d3js.org/d3.v4.min.js"></script>
That formatted date is useful for creating axes, tooltips, texts etc..., that is, showing the date you have without showing all its details. You can choose what information you want to show to the user (just the year, or just the month, or maybe day-month-year, whatever).
That's the difference between parsing and formatting.
Why using a formatter?
To finalise, you may ask: why am I using a formatter, if I will end up having the same thing I had at the beginning?
The answer is: you don't have the same thing. Now you have a date, not a string. And, using a date with a time scale, you can accomodate daylight savings, leap years, February with only 28 days, that is, a bunch of things that are impossible to do with a simple string.
PS: The demos above use D3 v4.
EDIT: After your update we can easily see the problem with your code: you have to pass an array to range().
var xScale = d3.time.scale().range([0,width]);
Here is the updated bl.ocks: http://bl.ocks.org/anonymous/a05e15339f7792f175d2bcebccf6bbed/7f23db481f1308eb0d5a1834f7cbc0b17d948167
Moment.js is a very usefull JavaScript library which provides many functions to manipulate date formatting.
In order to create a Moment object, it is possible to parse a string simply moment("1995-12-25"); or by providing format moment("12-25-1995", "MM-DD-YYYY");.
Another feature allows us to use relative dates : moment("1995-12-25").fromNow() // 19 years ago.
However, I can not find a way to parse such a relative date. When I try moment("19 years ago") it just returns Invalid date, and it does not exist any token to properly format the date.
Is there an easy way to do this? Or is it a missing feature that should be suggested on Github?
Just found chrono wile looking to see if NLP had already been implemented in momentjs. It looks like it handles parsing NLP to a date, which can be used to create a momentjs date.
Simply pass a string to function chrono.parseDate or chrono.parse.
> var chrono = require('chrono-node')
> chrono.parseDate('An appointment on Sep 12-13')
Fri Sep 12 2014 12:00:00 GMT-0500 (CDT)
And a quick example showing how that would work
Code
const moment = require('moment')
const chrono = require('chrono-node')
let now = moment()
console.log(now)
let yrsAgo = chrono.parseDate("19 years ago")
console.log(yrsAgo)
let yrsAgoMoment = moment(yrsAgo)
console.log(yrsAgoMoment)
Output
$node test.js
moment("2017-06-30T08:29:20.938")
1998-06-30T17:00:00.000Z
moment("1998-06-30T12:00:00.000")
The only way of doing this is moment().sub(19, 'years');
What you are asking imply a Natural language processing which is whole computer science field.
There is a plugin which very recently appeared on github, which is a plugin to moment to allow this sort of parsing: https://github.com/cmaurer/relative.time.parser
I have not personally tried it, but I will shortly (found both it and this question while searching for the same thing).
What about :
moment.fn.parse = function(_relative, _format){
var _modulo = moment.normalizeUnits(_format);
return this.add(_relative, _modulo);
}
moment("30/08/2015", "DD/MM/YYYY").parse(-20, "years").format('DD/MM/YYYY'); // 30/08/1995
moment("30/08/2015", "DD/MM/YYYY").parse(-2, "week").format('DD/MM/YYYY'); // 16/08/2015
moment("30/08/2015", "DD/MM/YYYY").parse(-2, "d").format('DD/MM/YYYY'); // 28/08/2015
I wrote the plugin relative.time.parser. The original intent was to parse relative time from graphite from/until, so I was only going for the 'reverse' in time.
I will take a look at adding the 'NLP' use cases as well.
Thanks,
Chris
You can do it easily using moment plus little logic. Here it is working perfectly
function parseSincUntilDate(dateStr, now = new Date()) {
// inputs: 20 minutes ago, 7 hours from now, now, '', or UTC string
if (moment(dateStr).isValid()) return moment(dateStr).toDate();
const tokens = dateStr.split(' ');
if (dateStr.includes('ago')) {
return moment(now).subtract(tokens[0], tokens[1]).toDate();
} else if (dateStr.includes('from now')) {
return moment(now).add(tokens[0], tokens[1]).toDate();
} else if (dateStr === 'now' || dateStr === '') {
return new Date(now);
}
return moment(dateStr).toDate();
}
// to change relative date, pass it in second parameter
As of Moment.js 1.0.0 (October 2011) to current:
moment().add(7, 'days');
moment().subtract(1, 'seconds');
Works with years, quarters, months, weeks, days, hours, minutes, seconds, and milliseconds.
https://momentjs.com/docs/#/manipulating/add/
https://momentjs.com/docs/#/manipulating/subtract/
I'm using moment.js 1.7.0 to try and compare today's date with another date but the diff function is saying they are 1 day apart for some reason.
code:
var releaseDate = moment("2012-09-25");
var now = moment(); //Today is 2012-09-25, same as releaseDate
console.log("RELEASE: " + releaseDate.format("YYYY-MM-DD"));
console.log("NOW: " + now.format("YYYY-MM-DD"));
console.log("DIFF: " + now.diff(releaseDate, 'days'));
console:
RELEASE: 2012-09-25
NOW: 2012-09-25
DIFF: 1
Ideas?
Based on the documentation (and brief testing), moment.js creates wrappers around date objects. The statement:
var now = moment();
creates a "moment" object that at its heart has a new Date object created as if by new Date(), so hours, minutes and seconds will be set to the current time.
The statement:
var releaseDate = moment("2012-09-25");
creates a moment object that at its heart has a new Date object created as if by new Date(2012, 8, 25) where the hours, minutes and seconds will all be set to zero for the local time zone.
moment.diff returns a value based on a the rounded difference in ms between the two dates. To see the full value, pass true as the third parameter:
now.diff(releaseDate, 'days', true)
------------------------------^
So it will depend on the time of day when the code is run and the local time zone whether now.diff(releaseDate, 'days') is zero or one, even when run on the same local date.
If you want to compare just dates, then use:
var now = moment().startOf('day');
which will set the time to 00:00:00 in the local time zone.
RobG's answer is correct for the question, so this answer is just for those searching how to compare dates in momentjs.
I attempted to use startOf('day') like mentioned above:
var compare = moment(dateA).startOf('day') === moment(dateB).startOf('day');
This did not work for me.
I had to use isSame:
var compare = moment(dateA).isSame(dateB, 'day');