Desi Delite Desi Delite - 1 year ago 304
jQuery Question

How to convert UTC date time into yyyy-mm-dd hh:mm:ss date time format using javaScript?

This is very simple question.There is a description inside a div tag and it contain a date time(format is yyyy-mm-dd hh:mm:ss). I catched this date time using regular expression and then convert into date.

Suppose I have "Now 2015-01-02 11:47:50 some statements.....".So after all, I wished to get "2015-01-02 11:47:50" part only. But Now I received it as "Fri Jan 02 2015 03:47:50 GMT-0800 (Pacific Standard Time)".

Where was I wrong? Can anyone please give me a advice to get the result as yyyy-mm-dd hh:mm:ss format?

Thank you..

(Here I attached the code I tried)

var getDiv = document.getElementById('aasd');
var aa = getDiv.innerHTML;
var result = dateCatcher(aa);

//Gives the date part from the whole statement
function dateCatcher(statement){

var date_finder =/(\d{4})\-(\d{2})\-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})/;
var datePart = statement.match(date_finder);
datePart[2] -= 1;
var UtcDate = new Date(Date.UTC.apply(this, datePart.slice(1)));
return UtcDate;

<div id = "aasd"> Hi, Now 2015-01-02 11:47:50 ddfd dfdsfdf dff </div>



Answer Source

I would suggest this as a solution:

var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var hours = dateObj.getUTCHours();
var minutes = dateObj.getUTCMinutes();
var seconds = dateObj.getUTCSeconds();
var newdate = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;

$('#time').append('Time is: ' + newdate);
<script src=""></script>
<p id="time"></p>

You can check this too. It might be helpful: Complete list of date object functions: DATE


Returns the month (0-11) in the specified date according to local time.


Returns the month (0-11) in the specified date according to universal time.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download