get Javascript date formatted as 2011-04-01

喜欢而已 提交于 2019-12-08 06:52:43

问题


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.


回答1:


   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;
    }



回答2:


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());
  }
}());



回答3:


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.




回答4:


also:

Convert javascript to date object to mysql date format (YYYY-MM-DD)

-- pete




回答5:


I think you are looking for this




回答6:


This nice code covers all types of formats

use this syntax

var now = new Date();
now.format("mm/dd/yyyy");


来源:https://stackoverflow.com/questions/5512476/get-javascript-date-formatted-as-2011-04-01

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!