繁体   English   中英

Javascript从日期中删除日期名称

[英]Javascript Remove Day Name from Date

我想问一下是否有人知道如何从以下示例中删除日期名称,警报返回 2020 年 2 月 29 日星期六,我不使用 Moment.js 仅 Jquery,因为我只需要能够以以下格式处理日期下面写成代码。

var mydate = new Date('29 Feb 2020');
alert(mydate.toDateString());

感谢您阅读这个问题,希望我清楚我的问题是什么

Date#toDateString方法将导致始终以该特定格式返回。

因此,要么您需要使用其他可用方法生成,要么您可以使用多种方法删除,


1. 使用String#split , Array#sliceArray#join

 var mydate = new Date('29 Feb 2020'); // split based on whitespace, then get except the first element // and then join again alert(mydate.toDateString().split(' ').slice(1).join(' '));


2. 使用String#replace

 var mydate = new Date('29 Feb 2020'); // replace first nonspace combination along with whitespace alert(mydate.toDateString().replace(/^\\S+\\s/,''));


3. 使用String#indexOfString#substr
 var mydate = new Date('29 Feb 2020'); // get index of first whitespace var str = mydate.toDateString(); // get substring alert(str.substr(str.indexOf(' ') + 1));

如果您有一个 Date 对象实例并且只想要它的某些部分,我会使用Date 对象 API

mydate.getDate() + ' ' + mydate.toLocaleString('en-us', { month: "short" }) + ' ' + mydate.getFullYear()

请记住,函数是基于本地时间的(有 UTC 变体,例如getUTCDate() ),同时为了防止混淆, getMonth()是基于零的。 在 JavaScript 中处理日期才是真正有趣的开始;)

toLocaleString函数虽然相对较新(IE11+),如果您需要支持旧浏览器,请检查其他可能性

最简单的方法是替换字符串中的所有字母字符。 这样,一旦天名处于不同的位置,您就不会出错。

 var withoutDay = '29 Feb 2020'.replace(/[a-zA-Z]{0,1}/g,'').replace(' ', ' '); alert(withoutDay);

代码replace(/[a-zA-Z]{0,1}/g,'')将替换字符串中的所有字母字符并replace(' ', ' '); 将删除双空格。

我希望这有帮助。

正确的方法是使用 DateTimeFormat。 您可以通过操作 DateTimeFormat 中的格式对象来进行操作。

 let myDate = new Date('29 Feb 2020'); let formattedDate = new Intl.DateTimeFormat("en-US", { year: "numeric", month: "short", day: "2-digit", }).format(myDate); alert(formattedDate)

暂无
暂无

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

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