我们如何在javascript中将日期转换为字符串(不是日期字符串)? [英] How can we convert a date to string (not date string) in javascript?

查看:120
本文介绍了我们如何在javascript中将日期转换为字符串(不是日期字符串)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库中检索了一个日期.我想将其转换为字符串,因为我想应用一些字符串属性/方法来进行一些格式化.
例子,

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,

var dt = " + dateFromDatabase;
//OR,
var dt = dateFromDatabase.toString();


变成这样,
2010年3月22日星期一18:43:00 UTC + 0530

我知道这很正常.
但是如何将其转换为字符串,例如"3/22/2010 6:43:00 PM".

任何帮助将不胜感激.

标记-这是解决方法,而不是解决方案.
该存储过程也由不需要格式化的其他页面使用.所以我不考虑编辑sp.
我正在ASP上开发此页面.我真的很想念.NET! :((
[/Edit]


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.

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]

推荐答案

看着它,看起来真的没有直接获取它的直接方法!
可能您必须这样做,看上去效果不错但可以使用.

创建一个带有日期并获取单个天/月/年/时间的方法,并将其附加为字符串并返回.
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.
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;
} 


另一种选择是使用在此处找到的脚本: JavaScript日期格式 [ ^ ].看来此脚本可以为您提供很大的灵活性.
Another option is to use the script found here: JavaScript Date Format[^]. Looks like this script would give you a lot of flexibility.


如果您从数据库中获取了该脚本,请先将其转换,然后再返回javascript.
If your getting it from the database then convert it before returning to javascript.


这篇关于我们如何在javascript中将日期转换为字符串(不是日期字符串)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆