我试图以数字格式获取jQuery中的日期和时间,例如,
yyyyMMddhhmm或者你可以说201404051159
这就是我想要的,
$(document).ready(function () {
var currentdate = new Date();
var datetime = currentdate.getDate() + ""
+ currentdate.getHours() + ""
+ currentdate.getMinutes();
alert(datetime);
});
它没有给我正确的约会
答案 0 :(得分:1)
这里有两个问题。
首先,您在没有先声明的情况下使用currentdate
变量。通过添加var currentdate = new Date();
其次,Date
对象上的getter方法不返回前导零。这意味着您需要获取该值并检查它是否小于9.如果是,则需要添加前导零。
类似的东西:
$(document).ready(function () {
var currentdate=new Date() // Declare date variable
var datetime = "" + currentdate.getFullYear();
var month = currentdate.getMonth() + 1; // Month is 0-11, not 1-12
if (month < 10) {
month = '0' + month;
}
datetime += month;
var day = currentdate.getDate();
if (day < 10) {
day = '0' + day;
}
datetime += day;
var hours = currentdate.getHours();
if (hours < 10) {
hours = '0' + hours;
}
datetime += hours;
var minutes = currentdate.getMinutes();
if (minutes < 10) {
minutes = '0' + minutes;
}
datetime += minutes;
var seconds = currentdate.getSeconds();
if (seconds < 10) {
seconds = '0' + seconds;
}
datetime += seconds;
alert(datetime);
});
答案 1 :(得分:0)
您错过了声明日期变量
试试这个
$(document).ready(function () {
var currentdate=new Date() // Declare date variable
var datetime = currentdate.getDate() + ""
+ currentdate.getHours() + ""
+ currentdate.getMinutes() + ""
+ currentdate.getSeconds();
alert(datetime);
});
答案 2 :(得分:0)
您忘记声明日期对象以访问日期
var date=new Date();
var datetime = date.getDate() + ""
+ date.getHours() + ""
+ date.getMinutes() + ""
+ date.getSeconds();
找到小提琴链接:
答案 3 :(得分:0)
试试这样:
$(document).ready(function () {
var currentdate = new Date();
var datetime = currentdate.getFullYear()
+ currentdate.getMonth()
+ currentdate.getDate()
+ currentdate.getHours()
+ currentdate.getMinutes()
alert(datetime);
});
答案 4 :(得分:0)
你可以这样分解
DEMO1 http://jsfiddle.net/YN2Xs/5/
OUTPUT1 20143593653
DEMO2 http://jsfiddle.net/YN2Xs/7/(带零的2位数)
OUTPUT2 2014030595829
EXAMPLE1
$(document).ready(function () {
var currentdate=new Date()
var datetime =
+ currentdate.getFullYear() + ""
+ currentdate.getMonth() + ""
+ currentdate.getDate() + ""
+ currentdate.getHours() + ""
+ currentdate.getMinutes() + ""
+ currentdate.getSeconds();
});
示例2,每天2位数添加0
所需
$(document).ready(function () {
var currentdate=new Date();
var month = currentdate.getMonth();
var day = currentdate.getDate();
if(month < 10){ month = '0' + month}
if(day < 10){ day = '0' + day}
var datetime =
+ currentdate.getFullYear() + ""
+ month + ""
+ day + ""
+ currentdate.getHours() + ""
+ currentdate.getMinutes() + ""
+ currentdate.getSeconds();
$('input').val(datetime);
});
EDITED
getFullYear()
已取代getYear()