moment.js get current time in milliseconds? - javascript

var timeArr = moment().format('HH:mm:ss').split(':');
var timeInMilliseconds = (timeArr[0] * 3600000) + (timeArr[1] * 60000);
This solution works, test it, but I'd rather just use the moment api instead of using my own code.
This code returns TODAYS time in milliseconds. I need it to call another function in milliseconds...Can not use the epoch. Need today's time formated in milliseconds. 9:00am = 3.24e+7 milliseconds 9:00pm = 6.84e+7 milliseconds.

From the docs:
http://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/
So use either of these:
moment(...).valueOf()
to parse a preexisting date and convert the representation to a unix timestamp
moment().valueOf()
for the current unix timestamp

See this link http://momentjs.com/docs/#/displaying/unix-timestamp-milliseconds/
valueOf() is the function you're looking for.
Editing my answer (OP wants milliseconds of today, not since epoch)
You want the milliseconds() function OR you could go the route of moment().valueOf()

var timeArr = moment().format('x');
returns the Unix Millisecond Timestamp as per the format() documentation.

You could subtract the current time stamp from 12 AM of the same day.
Using current timestamp:
moment().valueOf() - moment().startOf('day').valueOf()
Using arbitrary day:
moment(someDate).valueOf() - moment(someDate).startOf('day').valueOf()

You can just get the individual time components and calculate the total. You seem to be expecting Moment to already have this feature neatly packaged up for you, but it doesn't. I doubt it's something that people have a need for very often.
Example:
var m = moment();
var ms = m.milliseconds() + 1000 * (m.seconds() + 60 * (m.minutes() + 60 * m.hours()));
console.log(ms);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Since this thread is the first one from Google I found, one accurate and lazy way I found is :
const momentObject = moment().toObject();
// date doesn't exist with duration, but day does so use it instead
// -1 because moment start from date 1, but a duration start from 0
const durationCompatibleObject = { ... momentObject, day: momentObject.date - 1 };
delete durationCompatibleObject.date;
const yourDuration = moment.duration(durationCompatibleObject);
// yourDuration.asMilliseconds()
now just add some prototypes (such as toDuration()) / .asMilliseconds() into moment and you can easily switch to milliseconds() or whatever !

Related

Get current timestamp from a specific timezone in javascript

I'm trying to get a timestamp from a specific timezone that is independent of the local time.
I want my clients from all over the world to see the exact same timestamp. Is this even possible? I don't want a solution in node.js but if there is a working library, please include it.
You can either generate a timezone independent timestamp by means of JavaScript, using Date object, or using specialized libraries such as moment.js:
const timestampMilliseconds = (new Date()).getTime();
console.log(timestampMilliseconds);
const timestampSeconds = Math.round((new Date()).getTime() / 1000);
console.log(timestampSeconds);
const timestampSecondsMoment = moment().unix();
console.log(timestampSecondsMoment)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
You say that you want to get a timestamp for a "specific time zone". If you know what the time zone offset is for that specific time zone then you should be able to get a UTC date, subtract the time zone offset from it and output a date string that should be the same on all clients. This statement should work:
var timeZoneOffset = 300; // Eastern Standard Time
var sameDate = (new Date(((new Date()) - (timeZoneOffset * 60 * 1000)))).toISOString()
new Date() should return the same time in milliseconds on all clients if the date and time of the local machines are accurate. Time zone offsets are in minutes so you need to multiply them be 60 * 1000 (60 seconds/minute times 1000 milliseconds/second) and then subtract that many milliseconds from the UTC date to get it to equal the current time in the time zone that has that offset. Then convert it to an ISO string. You can manipulate the resulting string if you want. Perhaps get rid of the Z on the end.
var dateWithoutZ = sameDate.slice(0,-1);

Incorrect time while copy pasting a date time value using google apps script [duplicate]

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.

Convert exact date to time ago using jquery - What format for the date?

I have a static page which will specify a hardcoded exact date. If the use has javascript, I want to then convert this hardcoded exact date into a "time ago".
For example:
3 hours ago
My question is, in what format of date will javascript be able to most efficiently convert to the time ago?
10/10/13
10.10.13
10th October 2013
101013
I would look at this post: https://stackoverflow.com/a/3177838/2895307
In it he just uses a javascript Date() as the parameter to the "timeSince()" function. To create a javascript Date from your hardcoded string you can use this format:
var d1 = new Date("October 13, 1975 11:13:00")
definitely unix timestamp is the best format for all date and time calculations, you can convert the results to a more readable format later.
the calculation is simple, you start with the timestamp of an event in the past, for example:
var anHourAgo = Date.now() - 3600000;
then you substract that from the current timestamp and get the number of milliseconds that have passed since that event
Date.now() - anHourAgo
then you can pass that to any function that will convert those milliseconds to hours, minutes and seconds, here's an example that takes seconds and returns an array with that info, and another function that pads those numbers with zeros
var zeroPad = function(n){
return n.toString().replace(/^(\d)$/,'0$1');
};
var formatSecs = function(s){
var r = [
Math.floor(s / 3600),
Math.floor(s%3600 / 60),
Math.floor((s%3600)%60)
];
r.push(zeroPad(r[0])+':'+zeroPad(r[1])+':'+zeroPad(r[2]));
return r;
};
the formatSecs function expects seconds instead of millseconds, you should divide by 1000 and round that number, then pass that number to the function
Math.round(Date.now() - anHourAgo) / 1000
Finally here's a working example of all that code in action:
http://codepen.io/DavidVValdez/pen/axHGj
i hope this helps, cheers!
The easiest thing to do would be to use Date.getTime().
This will give you the number of milliseconds since the Unix epoch and will make the math very simple.
Date.getTime

JQuery datetime to milliseconds

I have a web application where I wish to send information to a database.
I have a datepicker, which lets the user select a date and formats the date as "YYYY-MM-DD". In addition to this, the users must also select a time using a timepicker which formats the time as "HH:MM". This gets concatenated into a DateTime string as "YYYY-MM-DD HH:MM".
I need to convert this into milliseconds for the datetime to be accepted as the correct format on the database (locale format of YYYY-MM-DD HH:MM:SS.mmm).
I have a tried a host of solutions found here and elsewhere to try and convert into milliseconds. Whenever I try to concat then convert I usually get a NaN error or "invalid Date" and I cannot simply add the converted milliseconds.
Is there any way of doing this in jQuery or JavaScript?
>> var datetime = new Date();
undefined
>> datetime.getTime();
1332613433314
Date.getTime() returns the number of milliseconds since 1970/01/01:
This should be handled server-side, though.
I managed to figure this one out myself. Thanks to those who answered. Its not an ideal solution, but it works.
var d = $("#date").val();
var dateParts = new Date((Number(d.split("-")[0])), (Number(d.split("-")[1]) - 1), (Number(d.split("-")[2])));
var dateis = dateParts.getTime();
var timeEnd = $("#endtime").val();
var time1 = ((Number(timeEnd.split(':')[0]) * 60 + Number(timeEnd.split(':')[1]) * 60) * 60) * 1000;
var timeStart = $("#starttime").val();
var time2 = ((Number(timeStart.split(':')[0]) * 60 + Number(timeStart.split(':')[1]) * 60) * 60) * 1000;
var dateTimeEnd = dateis + time1;
var dateTimeStart = dateis + time2;
What this basically does, is take a date from a datepicker, and a start and an endtime from a timepicker. The ajax accepts 2 datetimes, one for start, one for end. The above solution basically gets all the values from the input values, and converts it to milliseconds. It's not the best way of doing things but it is a quick fix.
I don't realise your actual question, but I've made a code that set the datepicker to a minimum selected day as today the code is as follows :
$("#datefield").datepicker({
dateFormat:"yy-mm-dd",
minDate:new Date(new Date().getTime())
});
The return value of the new Date().getTime() is the milliseconds from 1970/01/01 05:30 am (as my system)
Can you use the JavaScript Date object?
You could use it like so:
var d = new Date(yyyy, MM, dd, hh, mm, 0, 0).getTime();
You initialize the Date object and then use the getTime function to return the number of milliseconds since Jan. 1, 1970.
$("#datefield").datepicker("getDate").getTime(); will do the trick
I would do this on the server side and use the strtotime function to convert to a timestamp which will give you a number of seconds which if you really need milliseconds for some kind of script : 1 second = 1000 milliseconds.
If anything you could use jquery to validate that you'll be sending a valid date-time to the server side script before you do so.

javascript unixtime one minute in front

Hi I'm passing a unixtimestamp to a javascript IF statement, can anyone tell me how to generate a unixtimestamp one minute in the future with javascript.
Anyhelp would be helpful.
Thanks
The JavaScript Date object has a getTime() method that returns milliseconds since 1970. To make this look like a UNIX timestamp, you need to divide by 1000 and round (with Math.floor()). Adding 60 get's your one minute ahead.
var d = new Date();
var unixtimeAdd60 = Math.floor(d.getTime()/1000)+60;
UNIX time is just the number of seconds since 1970-01-01Z. So just add 60 you'll get a timestamp one minute later.
JavaScript Date object's getTime returns the number of milliseconds since midnight Jan 1, 1970.
Try this.
var oneMinLater = new Date().getTime() + 60 * 1000;
var d = new Date();
d.setTime(oneMinLater);
Another way to get the unix timestamp (this is time in seconds from 1/1/1970) in a simple way its:
var myDate = new Date();
console.log(+myDate + 60); // you just sum the seconds that you want
// +myDateObject give you the unix from that date

Categories