简体   繁体   中英

Javascript - Convert ####-##-## to Epoch time

Is there a way to take a date object from a HTML object in the format of ####-##-## and convert it to epoch time. For example, the user inputs the value of August 12, 2012 which shows as 2012-08-12 when I print out the .val() of it, and I need to get this in Epoch time.

EDIT

Code to date:

if (hvStartDate == "") {
    hvStartDate = "start"
} 
else {
    console.log($("#hv-start-date").val()); // => 2012-08-20
    hvStartDate = new Date($("#hv-start-date").val()).getTime(); // => NaN
}
if (hvEndDate == "") {
    hvEndDate = "end"
} 
else {
    hvEndDate = new Date($("#hv-end-date").val()).getTime(); // => NaN
}

var myTmp = new Date("2012-08-20");
console.log(myTmp.getTime()); // => NaN

Javascript's Date built-in allows you to pass a date string into its constructor, giving you a Date based on that string. From there, calling getTime( ) will give you the epoch time.

new Date($('.user-value').val()).getTime();  // => epoch time
new Date('2012-08-12').getTime();  // 1344729600000

Caveat: Beware of locale strings and locale-specific date formatting (for example, the position of days and months switch depending on locale).

EDIT: Based on your code in the comment below, here's what you need to do. Notice that you have to instantiate a new Date Object before calling getTime() :

if (hvStartDate == "") {
    hvStartDate = "start"
} 
else {
    hvStartDate = new Date($("#hv-start-date").val()).getTime();
}

Simply use the getTime() function. It returns the number of milliseconds since Epoch :

  var msSinceEpoch = myDate.getTime();

Complete Date reference at MDN : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date

EDIT : if you have to parse it too, you may :

  • use new Date(theString) if it has the good format
  • set yourself the different date fields (see reference) after having parsed it
  • use a date parsing library. I use this one : http://www.datejs.com/ which is very powerful for all date parsing, computing and formating.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM