简体   繁体   中英

Better way to deal with date in javascript

I have a form where the user has to input one begin date and one end date. After that, I have to compute the result of this date to have a status on the UI:

  • if dates are in the past, status is "DONE"
  • if dates are in the future, status is "TO BE DONE"
  • if today is bewteen the two dates, status is "IN PROGRESS"

How can I compute that easely? I have date in the form with that format: 04/21/2015.

Do you recommand me to compare date by changing format (04/21/2015 => 20150421) and compare? Or use Date of JS? or anything else?

Thanks in advance

Get two date objects like this:

// parse a date in mm/dd/yyyy format
function parseDate(input) {
  var parts = input.split('/');
  // new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[2], parts[0]-1, parts[1]); // Note: months are 0-based
}

Then compare using usual operators < > ==

You can create a date object for the input date and another date object for the current date and then, simply compare them.

Check the dateObject in order to provide the correct date string format:

var inpDate = $('input').val();
var d = new Date(inpDate);
var today = new Date();

if (inpDate > today) {
   return "TO BE DONE";
} else .... 

have you tried http://momentjs.com/ . Real easy to use, conversion and formatting could save you time adding further JavaScript code however it is offset by adding the library.

function getStatusByDate(startDate, endDate) {
    var currentTime = new Date().getTime();
    var startTime = new Date(startDate).getTime();
    var endTime = new Date(endDate).getTime();
    console.log(startTime, endTime);
    if (startTime < endTime && endTime < currentTime) {
        return ('DONE');
    } else if (startTime < endTime && endTime > currentTime && startTime < currentTime) {
        return ('IN PROGRESS');
    } else if (startTime < endTime && startTime > currentTime) {
        return ('TO BE DONE');
    } else {
        return ('INVALID INPUT');
    }
}

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