peter.o
peter.o

Reputation: 3530

Javascript date - Specify incoming date format (jQuery UI DateTimepicker)

I'm using custom plugin for jQuery UI datepicker - Timepicker

I have two fields, from and to input field, and need to check if to "is greater than" from. I have my custom onClose function (onClose: function(dateText, inst) {}), but the first parameter is value of input - a date string. But my date string is not in the "valid" JS datetime format so I'm not able to get Date object instance and compare.

It's dd.mm.yyyy hh:mm, e.g. 06.08.2012 12:00

I wonder if there is anything how to specify input string format, e.g.:

var date = new Date('dd.mm.yyyy hh:mm', dateText);

If not I'll have you parse it somehow...

Thanks for help in advance.

Upvotes: 0

Views: 1000

Answers (1)

maerics
maerics

Reputation: 156444

There is no such utility built in to JavaScript. If I were you I would match the date format with a regex and use the form of the Date constructor which accepts date parts:

function parseDate(str) {
  var m = str.match(/^(\d\d)\.(\d\d)\.(\d{4}) (\d\d):(\d\d)$/);
  return (m) ? new Date(m[3], m[2]-1, m[1], m[4], m[5]) : null;
}

Note that the month part is zero based (instead of one based, so January=0, hence the minux one). Also, note that the Number constructor is used to convert strings to numbers so you don't have to worry about numbers possibly prefixed with a zero being interpreted as octal as can happen with parseInt(...).

Upvotes: 1

Related Questions