Jaret Burkett
Jaret Burkett

Reputation: 123

How to format a date pulled from a form field with javascript

I have a date picker that generates a date like 6/30/2012 in a form field.

I need to convert this date to 2012-06-30 for mysql. I can get it close with the following.

var datePart=document.getElementById('formdate').value.split(/[^0-9]+/);

and then use to generate the date.

datePart2[2] + "-" + datePart2[1] + "-" + datePart2[0]

The problem is it gived me the date 2012-6-30 instead of 2012-06-30.

Is there an easier way to do this? Or a way to use my current method and ad a zero to the front of a digit if it is a single digit?

Upvotes: 1

Views: 992

Answers (4)

RobG
RobG

Reputation: 147403

Based on your example, a simple function is:

var formatUStoISOdate = (function() {

  function aZ(n) {
    return (n<10? '0' : '') + n;
  }

  var re = /[^0-9]/;

  return function(d) {
    var d = d.split(re);
    return d[2] + '-' + aZ(d[0]) + '-' + aZ(d[1]);

    // or
    // return [d[2], aZ(d[0]), aZ(d[1])].join('-');
  }


}());

alert(formatUStoISOdate('3/31/2011')); // 2011-03-31

Upvotes: 0

ron tornambe
ron tornambe

Reputation: 10780

The Open Source date.js ( http://www.datejs.com/ )provides a really extensive framework for JavaScript dates, IMHO superior to the jQuery plug-in. It may be more than you need for this requirement, but I think it is a welcome addition to any JavaScript programmers's arsenal.

To format your example:

var mySqlDate = Date.parse('6/30/2012').toString('yyyy-MM-dd');

Upvotes: 1

Tats_innit
Tats_innit

Reputation: 34107

try this, hope this help:

Format date in jquery- from Sat Mar 03 2012 14:16:05 GMT+0530 to 03/03/2012

important you need to put a check condition like this one and if its less then 10 append 0 [code] date < 10 ? "0"+date : date; cheers!

something on the line of this:

function dateFormatFoo(){
var d = new Date();
date = d.getDate();
date = date < 10 ? "0"+date : date;
mon = d.getMonth()+1;
mon = mon < 10 ? "0"+mon : mon;
year = d.getFullYear()
return (date+"/"+mon+"/"+year);
}

Upvotes: 0

javram
javram

Reputation: 2645

Are you using jQuery? if so you could use the Date Format plugin, makes date manipulation easy

http://archive.plugins.jquery.com/project/jquery-dateFormat

Upvotes: 0

Related Questions