Stagleton
Stagleton

Reputation: 1060

Where is the error in my javascript? converting date formats

I'm trying to convert date formats in javascript. I get a string from a form and then try to convert it to a date object and then change the formats. How do I fix my code below so that the datetime which normally looks like this: 3/31/2012 00:00 gets converted so that it looks like this: 2012-03-31 00:00?

Here is what my code looks like:

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

}

EDIT: THere is no output with the code above, but when I change it to:

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
}

Then the alert output is: Values are: 3/31/2012 00:00 and 3/31/2012 23:59

Upvotes: 0

Views: 136

Answers (2)

Stagleton
Stagleton

Reputation: 1060

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

  }

This got me what I was looking for.

Upvotes: 0

Jassi Oberoi
Jassi Oberoi

Reputation: 1424

i think the error is you are not closed your function, check this code now and also change your function name

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

Upvotes: 2

Related Questions