0

In my web app user needs to fill the fields like date and time. In date they can enter a date in a format: d/m/yy or dd/mm/yy (unfortunately I can't control how exactly user will enter it)

And they can also pick a time from the drop-down list: 08:00am,8.30am, 09:00am,.... , 05:00 pm

Now, I am trying to convert time and date strings it into a valid date object using function below, but I am getting "Date isInvalid Date" output. How should I proceed with it?

  var timeStartString ="1970/01/01 "+ "10:00am";
  var st1 =createDate("1/12/2013",timeStartString); 
  Logger.log("Date is"+st1);

 function createDate(dateString,timeString)
    {
      var eventDate  = new Date(dateString);
      var eventTime  = new Date(timeString)

      message +="Date String:"+dateString + " timeString "+timeString;

      eventTime.setFullYear(eventDate.getFullYear());
      eventTime.setDate(eventDate.getDate());
      eventTime.setMonth(eventDate.getMonth()); 

      return eventTime;
    }

2 Answers 2

4

You may want to look into using the Moment.js library, which makes date parsing and manipulation in JavaScript a bit easier. More information on how to use it in Apps Script here. If the date format is consistent, then you can use a custom format string to parse it.

var date = moment('1970/01/01 10:00am', 'YYYY/MM/DD HH:mma').toDate();
Sign up to request clarification or add additional context in comments.

Comments

0

The Date class won't recognize the time if am or pm is directly attatched to the time. For example new Date("1/12/2013 10:00am") will return Invalid Date, whereas new Date("1/12/2013 10:00 am") will return Sat Jan 12 2013 22:00:00. It's a subtle difference, but that's the way the parser is built. You shouldn't need the createDate method at all if you concatenate the date with the properly formatted time string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.