簡體   English   中英

如何從日期 object 獲取年/月/日?

[英]How to get year/month/day from a date object?

alert(dateObj)給出Wed Dec 30 2009 00:00:00 GMT+0800

如何獲取格式為2009/12/30的日期?

var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();

newdate = year + "/" + month + "/" + day;

或者您可以設置新日期並給出上述值

new Date().toISOString()
"2016-02-18T23:59:48.039Z"
new Date().toISOString().split('T')[0];
"2016-02-18"
new Date().toISOString().replace('-', '/').split('T')[0].replace('-', '/');
"2016/02/18"

new Date().toLocaleString().split(',')[0]
"2/18/2016"
var dt = new Date();

dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();

由於月份索引基於 0,因此您必須將其增加 1。

編輯

有關日期對象函數的完整列表,請參見

日期

getMonth()

根據當地時間返回指定日期的月份(0-11)。

getUTCMonth()

根據世界時返回指定日期的月份(0-11)。

為什么不使用帶有slicetoISOString()方法或簡單地使用toLocaleDateString()

請注意, toISOString返回的時區始終為零 UTC 偏移量,而在toLocaleDateString中,它是用戶代理的時區。

在這里檢查:

 const d = new Date() // today, now // Timezone zero UTC offset console.log(d.toISOString().slice(0, 10)) // YYYY-MM-DD // Timezone of User Agent console.log(d.toLocaleDateString('en-CA')) // YYYY-MM-DD console.log(d.toLocaleDateString('en-US')) // M/D/YYYY console.log(d.toLocaleDateString('de-DE')) // DMYYYY console.log(d.toLocaleDateString('pt-PT')) // DD/MM/YYYY

我建議你使用 Moment.js http://momentjs.com/

然后你可以這樣做:

moment(new Date()).format("YYYY/MM/DD");

注意:如果您想要當前的 TimeDate,您實際上不需要添加new Date() ,我只是將它添加為您可以將日期對象傳遞給它的參考。 對於當前的 TimeDate 這也適用:

moment().format("YYYY/MM/DD");

2021年的答案

您可以使用本機.toLocaleDateString()函數,它支持幾個有用的參數,如語言環境(選擇 MM/DD/YYYY 或 YYYY/MM/DD 等格式)、時區(轉換日期)和格式詳細信息選項(例如: 1 vs 01 vs 一月)。

例子

new Date().toLocaleDateString() // 8/19/2020

new Date().toLocaleDateString('en-US', {year: 'numeric', month: '2-digit', day: '2-digit'}); // 08/19/2020 (month and day with two digits)

new Date().toLocaleDateString('en-ZA'); // 2020/08/19 (year/month/day) notice the different locale

new Date().toLocaleDateString('en-CA'); // 2020-08-19 (year-month-day) notice the different locale

new Date().toLocaleString("en-US", {timeZone: "America/New_York"}); // 8/19/2020, 9:29:51 AM. (date and time in a specific timezone)

new Date().toLocaleString("en-US", {hour: '2-digit', hour12: false, timeZone: "America/New_York"});  // 09 (just the hour)

請注意,有時要以您想要的特定格式輸出日期,您必須找到與該格式兼容的語言環境。 您可以在此處找到語言環境示例: https ://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all

請注意,語言環境只是更改格式,如果要將特定日期轉換為特定國家或城市時間,則需要使用時區參數。

var date = new Date().toLocaleDateString()
"12/30/2009"

信息

如果需要 2 位數的月份和日期(2016/01/01 與 2016/1/1)

代碼

var dateObj = new Date();
var month = ('0' + (dateObj.getMonth() + 1)).slice(-2);
var date = ('0' + dateObj.getDate()).slice(-2);
var year = dateObj.getFullYear();
var shortDate = year + '/' + month + '/' + date;
alert(shortDate);

輸出

2016/10/06

小提琴

https://jsfiddle.net/Hastig/1xuu7z7h/

信用

來自此答案的更多信息和信用

更多的

要了解有關.slice的更多信息,w3schools 的try it own 編輯器幫助我更好地理解了如何使用它。

使用日期獲取方法。

http://www.tizag.com/javascriptT/javascriptdate.php

http://www.htmlgoodies.com/beyond/javascript/article.php/3470841

var dateobj= new Date() ;
var month = dateobj.getMonth() + 1;
var day = dateobj.getDate() ;
var year = dateobj.getFullYear();
let dateObj = new Date();

let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate());

作為參考,您可以查看以下詳細信息

new Date().getDate()          // Return the day as a number (1-31)
new Date().getDay()           // Return the weekday as a number (0-6)
new Date().getFullYear()      // Return the four digit year (yyyy)
new Date().getHours()         // Return the hour (0-23)
new Date().getMilliseconds()  // Return the milliseconds (0-999)
new Date().getMinutes()       // Return the minutes (0-59)
new Date().getMonth()         // Return the month (0-11)
new Date().getSeconds()       // Return the seconds (0-59)
new Date().getTime()          // Return the time (milliseconds since January 1, 1970)

 let dateObj = new Date(); let myDate = (dateObj.getUTCFullYear()) + "/" + (dateObj.getMonth() + 1)+ "/" + (dateObj.getUTCDate()); console.log(myDate)

不錯的格式化插件:http: //blog.stevenlevithan.com/archives/date-time-format

有了它,你可以寫:

var now = new Date();
now.format("yyyy/mm/dd");

歐洲(英語/西班牙語)格式
我你也需要得到當天,你可以用這個。

function getFormattedDate(today) 
{
    var week = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    var day  = week[today.getDay()];
    var dd   = today.getDate();
    var mm   = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    var hour = today.getHours();
    var minu = today.getMinutes();

    if(dd<10)  { dd='0'+dd } 
    if(mm<10)  { mm='0'+mm } 
    if(minu<10){ minu='0'+minu } 

    return day+' - '+dd+'/'+mm+'/'+yyyy+' '+hour+':'+minu;
}

var date = new Date();
var text = getFormattedDate(date);


*對於西班牙語格式,只需翻譯 WEEK 變量。

var week = new Array('Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado');


輸出:星期一 - 2015 年 11 月 16 日 14:24

有了接受的答案,1 月 1 日將顯示如下: 2017/1/1

如果您更喜歡2017/01/01 ,可以使用:

var dt = new Date();
var date = dt.getFullYear() + '/' + (((dt.getMonth() + 1) < 10) ? '0' : '') + (dt.getMonth() + 1) + '/' + ((dt.getDate() < 10) ? '0' : '') + dt.getDate();

這是使用模板文字獲取年/月/日的一種更簡潔的方法:

 var date = new Date(); var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`; console.log(formattedDate);

它是動態的它將從用戶的瀏覽器設置中收集語言

使用選項對象中的分鍾小時屬性來處理它們。您可以使用值來表示月份,例如 Augest 23 等...

function getDate(){
 const now = new Date()
 const option = {
  day: 'numeric',
  month: 'numeric',
  year: 'numeric'
 }
 const local = navigator.language
 labelDate.textContent = `${new 
 Intl.DateTimeFormat(local,option).format(now)}`
}
getDate()

您可以簡單地使用這一行代碼以年-月-日格式獲取日期

var date = new Date().getFullYear() + "-" + new Date().getMonth() + 1 + "-" + new Date().getDate();

一個班輪,使用解構。

生成 3 個字符串類型的變量:

const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-')

生成 3 個類型為數字(整數)的變量:

const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-').map(x => parseInt(x, 10))

從那時起,您可以輕松地它們組合成任何您喜歡的方式:

const [year, month, day] = (new Date()).toISOString().substr(0, 10).split('-');
const dateFormatted = `${year}/${month}/${day}`;

如果您將日期 obj 或 js 時間戳傳遞給它,我正在使用它:

getHumanReadableDate: function(date) {
    if (date instanceof Date) {
         return date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear();
    } else if (isFinite(date)) {//timestamp
        var d = new Date();
        d.setTime(date);
        return this.getHumanReadableDate(d);
    }
}

ES2018 引入了正則表達式捕獲組,您可以使用它來捕獲日、月和年:

const REGEX = /(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2});
const results = REGEX.exec('2018-07-12');
console.log(results.groups.year);
console.log(results.groups.month);
console.log(results.groups.day);

這種方法的優點是可以捕獲非標准字符串日期格式的日、月、年。

參考。 https://www.freecodecamp.org/news/es9-javascripts-state-of-art-in-2018-9a350643f29c/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM