JQuery datetime to milliseconds - javascript

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.

Related

How do I get difference between two dates of unknown format in javascript?

I get a date as String from server like this: 2017-01-23T16:08:45.742Z. I want to find the difference in days, between this and the current date (or precisely, current time). I could just extract date alone (without time) and check, but I'd need a precise answer based on provided time & current time.
How do I achieve this?
Should be easy....
var dateFromServer = '2017-01-23T16:08:45.742Z'
var msInDay = 1000 * 60 * 60 * 24
var difference = (new Date(dateFromServer) - Date.now()) / msInDay
document.write('difference = ' + difference + ' days')
That date format looks like ISO_8061. https://en.wikipedia.org/wiki/ISO_8601
Use the Date object to get the difference between today and the other date in milliseconds, then divide by the number of milliseconds in a day.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
The code below can be condensed into a single line but I wanted to be explicit.
let date = "2017-01-23T16:08:45.742Z";
let d1 = new Date(date); // given date
let today = new Date(); // today's date
let diff = (d1 - today); // difference in milliseconds
let days = diff / 8.64e+7; // divide difference by 1 day in milliseconds
console.log(days)
Point of clarification: if I understand you correctly, you're actually trying to get the difference between two dates of different formats, not two dates of unknown formats. That's way easier.
Further, it looks like your server string is already stored in ISO format, which again makes this way easier.
I'd recommend looking at the JavaScript Date object. I believe in this case your best bet would be something like this:
// Your string from the server
var data_from_server = '2017-01-23T16:08:45.742Z';
// Create a new Date() object using the ISO string provided by your server
var olddate = new Date(data_from_server);
// Create a new empty Date() object, which should default to the current time
var currentdate = new Date();
// Subtract the two
var dif = currentdate.getTime() - olddate.getTime();
// Alert the result
alert(dif);

Comparing a datetime from a get request with the current date time in JavaScript

I need to get the difference (in minutes) from a datetime that I get froma get request in a string format to now.
According to my research, I can use moment.js to do so, but I haven't figured out now.
That format I am getting the date/time to be compared is as:
2017-02-10T20:52:13.885Z
I have already tried to do some operations with moment.js such as
moment().startof(comparedTime).fromNow())
But it returns nothing.
What are the alternatives and the best way to do this?
Can't you just use vanilla javaScript?
var getDate = '2017-02-10T20:52:13.885Z'; //get time from server
var parseDate = new Date(getDate).getTime(); //change string into Date object into milliseconds
var nowDate = Date.now(); //get current Date in milliseconds
var minutes = Math.round((nowDate-parseDate)/1000/60); //subtract times, count seconds (/1000), count minutes (/60)
console.log(minutes);
You need to create a moment object by passing the date string in. e.g.
myDate = moment(myISOString)
https://momentjs.com/docs/#/parsing/
Then you can use the moment object as described in the docs.
With Moment.js, this is simply:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes') // 65
If you want partial minutes included, then pass true as a third parameter:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes', true) // 65.04565

moment.js get current time in milliseconds?

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 !

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

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