Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I retrieved a date from database. I am trying to convert it to string as i want to apply some string properties/methods to do some formatting.
Example,
dateFromDatabase = 3/22/2010 6:43:00 PM

When I do,
JavaScript
var dt = " + dateFromDatabase;
//OR,
var dt = dateFromDatabase.toString();

it becomes like this,
Mon Mar 22 18:43:00 UTC+0530 2010

I know this is normal.
But how do i convert it a string i.e "3/22/2010 6:43:00 PM".

Any help would be greatly appreciated.
[Edit]
To Mark - That's a work around and not a solution.
The stored procedure is also used by a different page where formatting is not required. So I am not considering editing the sp.
I am developing this page on ASP. I am really missing .NET! :((
[/Edit]
Posted
Updated 25-Mar-10 2:58am
v3

Looked at it, looks like really no direct method to get as it is!
Probably you have to do it which will look little bad but will work.

Create your method that takes a date and get individual days/months/years/time and append it as a string and return it.
JavaScript
var d1 = new Date("3/22/2010 6:43:00 PM");
var d=GetStringDate(d1);
document.write("Converted Date:"+d);

function GetStringDate(tDate)
{
   strDate = (tDate.getMonth()+1) + "/" + tDate.getDate() 
             + "/" + tDate.getYear() + " " + getClockTime();
   return strDate;
}
function getClockTime()
{
   var now    = new Date();
   var hour   = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
   if (second < 10) { second = "0" + second; }
   var timeString = hour +
                    ':' +
                    minute +
                    ':' +
                    second +
                    " " +
                    ap;
   return timeString;
} 
 
Share this answer
 
v2
Another option is to use the script found here: JavaScript Date Format[^]. Looks like this script would give you a lot of flexibility.
 
Share this answer
 
If your getting it from the database then convert it before returning to javascript.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900