0

I'm using a DateTime Picker so that the info is presented in a readable format for the user, ie:

01/21/2014 10:45 PM

The input has a class of .start so when I get the value upon form submission:

$('.start').val();

I get a string: "01/21/2014 10:45 PM"

I'm trying to write a JS function that will convert that to a Datetime format before posting it to my database, ie:

2014-01-17 22:45:00

2
  • You can split the string on non-digit and non-alpha characters, adjust values that need it (e.g. hrs and am/pm), then format the string. Have a go, post your code, you'll get help. :-) Commented Jan 21, 2014 at 6:22
  • r u using any server side script like php? if yes you can convert it timestamp before submit in database Commented Jan 21, 2014 at 6:22

2 Answers 2

1

You can write a simple function like:

function stringToISOString(s) {
  var b = s.split(/[\/ :]/g);
  var t = b[b.length - 1].toLowerCase() == 'am'? 0 : 12;

  return b[2] + '-' + b[0] + '-' + b[1] + ' ' + (+b[3] + t) + ':' + b[4] + ':00';
}

console.log(stringToISOString('01/21/2014 10:45 PM')); //2014-01-17 22:45:00

however that assumes the minutes are always zero. You can test for that and set an approriate value if you wish, e.g.

function stringToISOString(s) {
  var b = s.split(/[\/ :]/g);
  var t = b[b.length - 1].toLowerCase() == 'am'? 0 : 12;

  // deal with minutes
  var mins = /^\d+$/.test(b[5])? b[5] : '00';

  return b[2] + '-' + b[0] + '-' + b[1] + ' ' + (+b[3] + t) + ':' + b[4] + ':' + mins;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Check this link - there is a function called getdatefromformat() which you can use for your date formatting.

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.