I've seen this: how to get formatted date time like 2009-05-29 21:55:57 using javascript?
but I do need the 0's before a single digit date(I need 2011-04-01, not 2011-4-1)
I don't like to add another unnecessary plugin for this one so if there's a builtin function or SIMPLE function in js/jquery that could do this, I'm good. I do hope it will not result to a 10 line function just to check if the month was singular and then add a zero to it.
Basically, I am using the AnyTime js (http://www.ama3.com/anytime/) plugin but it throws an error if my starting date was not in the form "yyyy-mm-dd". My starting default value is "now" so I am trying to convert a new Date() to that format. Any help?
NOTE
please don't give links of plugins as i was hoping for a REALLY simple solution. i find that using a plugin just to fix a plugin isn't actually very clean.
function getFormattedDate() {
var date = new Date();
var str = date.getFullYear() + "-" + getFormattedPartTime(date.getMonth()) + "-" + getFormattedPartTime(date.getDate()) + " " + getFormattedPartTime(date.getHours()) + ":" + getFormattedPartTime(date.getMinutes()) + ":" + getFormattedPartTime(date.getSeconds());
return str;
}
function getFormattedPartTime(partTime){
if (partTime<10)
return "0"+partTime;
return partTime;
}
vvk's effort is pretty much on the money, here's a minor modification of the same thing:
var getDate = (function() {
function addZ(n) {
return n<10? '0'+n : ''+n;
}
return function() {
var d = new Date();
return d.getFullYear()+'-'+addZ(d.getMonth()+1)+'-'+addZ(d.getDate());
}
}());
The Any+Time(TM) library includes an object named AnyTime.Converter specifically for parsing and formatting dates, so you could have done this:
(new AnyTime.Converter({format:"%Y-%M-%d"})).format(new Date());
However, the library also defaults to the current date/time if the field is empty or does not match the format specifier, so you really could just leave the field empty when you display the form!
If anyone has additional problems or questions, you can usually reach me directly via the links on my website.
also:
Convert javascript to date object to mysql date format (YYYY-MM-DD)
-- pete
I think you are looking for this
This nice code covers all types of formats
use this syntax
var now = new Date();
now.format("mm/dd/yyyy");