简体   繁体   English

JavaScript将日期转换为格式

[英]JavaScript convert date to format

I'm trying to truncate a JavaScript Date object string from: 我正在尝试从以下位置截断JavaScript Date对象字符串:

Wed Aug 01 2012 06:00:00 GMT-0700 (Pacific Daylight Time)

to

Wed Aug 01 2012

(I'm not particular, could be of format MM/DD/YYYY for example, as long as I get rid of the time/timezone) (我并不特别,例如,只要我摆脱了时间/时区,其格式可以是MM/DD/YYYY

Essentially I just want to get rid of the time and the timezone because I need to do a === comparison with another date (that doesn't include the time or timezone) 本质上,我只想摆脱时间和时区,因为我需要与另一个日期进行===比较(不包括时间或时区)

I've tried using this http://www.mattkruse.com/javascript/date/index.html but it was to no avail. 我已经尝试使用此http://www.mattkruse.com/javascript/date/index.html,但这没有用。 Does anyone know how I can format the existing string such as to get rid of the time? 有谁知道我如何格式化现有的字符串,例如摆脱时间? I would prefer to stay away from substring functions, but if that's the only option then I guess I'll have to settle. 我宁愿远离substring函数,但是如果这是唯一的选择,那么我想我必须解决。

Edit: I'm open to options that will compare two date objects/strings and return true if the date is the same and the time is different. 编辑:我愿意选择将比较两个日期对象/字符串并在日期相同和时间不同时返回true选项。

The only way to get a specific format of date across different browsers is to create it yourself. 在不同的浏览器中获取特定日期格式的唯一方法是自己创建日期。 The Date methods in ECMAScript are all implementation dependent. ECMAScript中的Date方法都依赖于实现。

If you have a date object, then: 如果您有日期对象,则:

// For format Wed Aug 01 2012
function formatDate(obj) {
  var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  var months = ['Jan','Feb','Mar','Apr','May','Jun',
               'Jul','Aug','Sep','Oct','Nov','Dec'];    
  return days[obj.getDay()] + ' ' + months[obj.getMonth()] + 
         ' ' + obj.getDate() + ' ' + obj.getFullYear();
}

Though a more widely used format is Wed 01 Aug 2012 尽管更广泛使用的格式是2012年8月1日星期三

Use the Date object's toDateString() method instead of its toString() method. 使用Date对象的toDateString()方法而不是其toString()方法。

SIDE BY SIDE DEMO 并排演示

Even so, it might be better to compare the two date objects directly: Compare two dates with JavaScript 即使这样,最好直接比较两个日期对象: 用JavaScript比较两个日期

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM