0

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.

1 Answer 1

1

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(...).

Sign up to request clarification or add additional context in comments.

5 Comments

Variable m is always null for me...I have no idea why. I've tested it with Reqular Expression Tester for Firefox
Check the input string very carefully. Does it have any additional whitespace (before? after? in between)?
I checked it there: regular-expressions.info/javascriptexample.html - it was OK. And then I tried if(!new RegExp(/^(\d\d)\.(\d\d)\.(\d{4})\s(\d\d):(\d\d)$/).test(str)) on my localhost and got error, that str is invalid. There are no white spaces around, maybe the one in the middle...
I've tried this approach. but still null...........var regex = '/^(\d\d)\.(\d\d)\.(\d{4}) (\d\d):(\d\d)$/'; var re = new RegExp(regex); var m = re.exec($.trim(str));
I've just moved this function from my template file to .js file and included in <head> and it's working :) Thanks a lot for help.

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.