[英]Javascript Remove Day Name from Date
我想問一下是否有人知道如何從以下示例中刪除日期名稱,警報返回 2020 年 2 月 29 日星期六,我不使用 Moment.js 僅 Jquery,因為我只需要能夠以以下格式處理日期下面寫成代碼。
var mydate = new Date('29 Feb 2020');
alert(mydate.toDateString());
感謝您閱讀這個問題,希望我清楚我的問題是什么
Date#toDateString
方法將導致始終以該特定格式返回。
因此,要么您需要使用其他可用方法生成,要么您可以使用多種方法刪除,
String#split
, Array#slice
和Array#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(' '));
String#replace
var mydate = new Date('29 Feb 2020'); // replace first nonspace combination along with whitespace alert(mydate.toDateString().replace(/^\\S+\\s/,''));
String#indexOf
和String#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.