繁体   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