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
Related
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 !
As you might know, you can display the time in JavaScript by doing Date() But can you display the Linux Epoch time in JavaScript?
I would like to know because I have a time converter and It would be nice to show the current Epoch time.
You have to use the .getTime() method of the Date object.
var d = new Date();
alert(d.getTime());
Epoch is also called timestamp.
Simple and straightforward.
var milliseconds = new Date().getTime();
Older browsers:
(new Date).getTime()
New way:
Date.now()
Returns in milliseconds, so epoch / 1000 | 0 to get seconds.
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
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.
I am trying to calculate the current second in the current month, but I'm having trouble creating a simple function that does it.
My best guess involves using getTime() - the current milliseconds since January 1 1970 - and then subtracting X, where X is the number of milliseconds up to the end of the previous month.
Can you help me think of a better way to do this?
Thank you very much for your help.
Cheers,
function() {
var now = new Date().getTime(),
monthStart = new Date();
monthStart.setDate(1);
monthStart.setHours(0);
monthStart.setMinutes(0);
monthStart.setSeconds(0);
monthStart.setMilliseconds(0);
return Math.floor((now - monthStart.getTime()) / 1000);
}
You can create a Date instance and then call methods to set everything back to 00:00:00 on the first day of the month. Then you'd subtract that from the "now" timestamp.
The methods you'd call are setDate(1) to set the day-of-month back to the start of the month, and then setHours(), setMinutes(), setSeconds(), and setMilliseconds(), passing all those zero.
Timestamps (return values from getTime() are in milliseconds, so you'll divide your difference by 1000 to get the seconds into the month.
You can create a new date set to the first day of the month, like so:
var start = Date.parse("2010-11-01");
Then you can create a date for today:
var today = Date.now();
Then you just subtract them:
var seconds_in_month = today - start;