Reputation: 2032
I want date format of 2014-07-24 17:35:00
to 24-07-2014 17:35:00
using JavaScript.
I tried this way,
datestring = '2014-07-24 17:35:00';
function formatDate(datestring) {
var m_names = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
var d = new Date(datestring);
//var d = new Date(datestring * 1000);
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var hours = d.getHours();
var minutes = d.getMinutes();
var result = curr_date + "-" +m_names[curr_month] + "-" + curr_year+' '+hours+':'+minutes;
alert(result);
return result;
}
But I am getting an error, NaN-undefined-NaN NaN:NaN
. Thanks for help.
Upvotes: 0
Views: 677
Reputation: 89
A solution bellow with less code:
function transformDate(dateString) {
var dateTimeParts = dateString.split(' ');
var dateParts = dateTimeParts[0].split('-');
return [[dateParts[2], dateParts[1], dateParts[0], ].join('-'), dateTimeParts[1]].join(" ");
}
var newDate = transformDate('2014-07-24 17:35:00');
console.log(newDate);
If you need more flexibility in your code, including working with localization you could consider moment.js library as well.
Upvotes: 0
Reputation: 106
i think you have simple way to solve this question.
Try this.
function myFunction() {
var d = new Date("2014-07-24 17:35:00");
var n = d.toLocaleDateString('en-GB');
var t = d.toLocaleTimeString('en-GB')
var r = n.replace(new RegExp('/', 'g'),'-')
document.getElementById("demo").innerHTML = replase +" "+t;
}
Upvotes: 1
Reputation: 885
I tried out your code and look what I found
var datestring = '2014-07-24 17:35:00';
$("#date").val(formatDate1())
$("#date2").val(formatDate())
function formatDate1(datestring) {
var m_names = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
var d = new Date(datestring);
//var d = new Date(datestring * 1000);
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var hours = d.getHours();
var minutes = d.getMinutes();
var result = curr_date + "-" +m_names[curr_month] + "-" + curr_year+' '+hours+':'+minutes;
return result;
}
function formatDate() {
var m_names = new Array("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
var d = new Date(datestring);
//var d = new Date(datestring * 1000);
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var hours = d.getHours();
var minutes = d.getMinutes();
var result = curr_date + "-" +m_names[curr_month] + "-" + curr_year+' '+hours+':'+minutes;
return result;
}
So your problem is parameter "datestring" because it's hiding variable with same name
here you can see an Fiddle example
Upvotes: 0