如何获得两位数的月份和日期

时间:2017-03-07 20:24:33

标签: javascript jquery date

我有一个由jQuery / JS填充的输入。目前,它使用类似2017-3-7的日期值填充输入,但我希望它为2017-03-07

我在这里有一个jsfiddle:https://jsfiddle.net/ua8rngzw/

代码如下:

(function ($) {
  $(document).ready(function() {
    var now = new Date();
    var created = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
    $('#created').val(created);
  });
})(jQuery);    

做这种事最简单快捷的方法是什么?

3 个答案:

答案 0 :(得分:5)

我们可以创建一个简单的函数,它接受一个值并根据它的长度,预先为它添加一个零。然后,获取日期部分并通过函数运行它们:



(function ($) {    
  $(document).ready(function() {
    var now = new Date();
    var created = now.getFullYear() + '-' + 
                  fixDigit(now.getMonth() + 1) + 
                  '-' + fixDigit(now.getDate());
    $('#created').val(created);
  });
      
  // Utility function to prepend zeros to single digits:
  function fixDigit(val){
    return val.toString().length === 1 ? "0" + val : val;
  }
})(jQuery);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="created">
&#13;
&#13;
&#13;

答案 1 :(得分:1)

(function ($) {
  $(document).ready(function() {
    var now = new Date();
    mo = now.getMonth() + 1;
    if (mo < 10) {
        mo = "0" + mo;
    }
    date = now.getDate();
    if (date < 10) {
            date = "0" + date;
        }

        var created = now.getFullYear() + '-' + mo + '-' + date;
    $('#created').val(created);
  });
})(jQuery);    

答案 2 :(得分:0)

可能的解决方案是:

dbServer = ''

def main():
    global dbServer
    SERVER_NAME=''
    PORT_NAME=''
    PASSWORD=''
    try:
        opts, args = getopt.getopt(sys.argv[1:],"hs:p:x:", ["server=","port=","password="])
    except getopt.GetoptError:
        print 'help'
        sys.exit(2)

    for o, a in opts:
        if o == '-h':
            print '\n'+'-s / --server (required)'  
            print '\n'+'-p or --port (required)'
            print '\n'+'-x or --password (required)'
            sys.exit()
        elif o in ("-s", "--server"):
            SERVER_NAME = a
        elif o in ("-p", "--port"):
            PORT_NAME = a
        elif o in ("-x", "--password"):
            PASSWORD = a
        else:
            assert False, "No command line option.  To see the options, plese use -h"

    print SERVER_NAME
    dbServer=SERVER_NAME    

if __name__ == "__main__":
    main()