我正在尝试在javascript中转换日期格式。我从表单中获取一个字符串,然后尝试将其转换为日期对象,然后更改格式。如何修复下面的代码,以便日期时间通常如下所示:3/31/2012 00:00 得到转换,看起来像这样:2012-03-31 00:00?
以下是我的代码:
function load(form) {
if (form != null){
var startdt = getDateFromFormat(form.datetime1.value,"MM/dd/yyyy hh:mm");
var enddt = getDateFromFormat(form.datetime2.value,"MM/dd/yyyy hh:mm");
startdt2 = dateFormat(startdt, "yyyy-MM-dd hh:mm");
enddt2 = dateFormat(enddt, "yyyy-MM-dd hh:mm");
//can be used for debugging but stops script
//var now = Date();
//now.format(MM/dd/yyyy hh:mm);
//want new format(yyyy-MM-dd hh:mm)
alert("Values are: " + startdt2 + " " + enddt2);
}
//rest of function
}
编辑: 以上代码没有输出,但当我将其更改为:
function load(form) {
if (form != null){
var startdt = form.datetime1.value;
var enddt = form.datetime2.value
//can be used for debugging but stops script
//var now = Date();
//now.format(MM/dd/yyyy hh:mm);
//want new format(yyyy-MM-dd hh:mm)
alert("Values are: " + startdt + " and " + enddt);
}
//rest of function edited out
}
然后警报输出是: 值为:3/31/2012 00:00和3/31/2012 23:59
答案 0 :(得分:2)
我认为错误是您没有关闭您的功能,现在检查此代码并更改您的功能名称
function change_name(form) {
if (form != null){
var startdt = getDateFromFormat(form.datetime1.value,"MM/dd/yyyy hh:mm");
var enddt = getDateFromFormat(form.datetime2.value,"MM/dd/yyyy hh:mm");
startdt2 = dateFormat(startdt, "yyyy-MM-dd hh:mm");
enddt2 = dateFormat(enddt, "yyyy-MM-dd hh:mm");
//can be used for debugging but stops script
//var now = Date();
//now.format(MM/dd/yyyy hh:mm);
//want new format(yyyy-MM-dd hh:mm)
alert("Values are: " + startdt2 + " " + enddt2);
}
}
答案 1 :(得分:0)
function load(form) {
if (form != null){
var startdt = new Date(form.datetime1.value);
var enddt = new Date(form.datetime2.value);
var startformat = startdt.getFullYear() + "-" + (startdt.getMonth()+1) + "-" + startdt.getDate() + " " + startdt.getHours() +":" + startdt.getMinutes();
var endformat = enddt.getFullYear() + "-" + (enddt.getMonth()+1) + "-" + enddt.getDate() + " " + enddt.getHours() +":" + enddt.getMinutes();
alert("Values are: " + startformat + " " + endformat);
}
//rest of function edited out for brevity
}
这让我得到了我想要的东西。