如何格式化JavaScript日期?
在JavaScript中,如何格式化日期对象以打印为如何格式化JavaScript日期?,javascript,date,date-formatting,Javascript,Date,Date Formatting,在JavaScript中,如何格式化日期对象以打印为2010年8月10日?对于自定义分隔的日期格式,必须提取日期(或时间) 对象中的组件(该对象是 ),然后手动创建字符串 使用所需的分隔符 要做到这一点,您可以使用。你可以 分解数组,但这并不理想,因为数组输出取决于 区域设置: {//示例1 设f=new Intl.DateTimeFormat('en'); 设a=f.formatoparts(); 控制台日志(a); } {//示例2 设f=new Intl.DateTimeFormat('
2010年8月10日
?对于自定义分隔的日期格式,必须提取日期(或时间)
对象中的组件(该对象是
),然后手动创建字符串
使用所需的分隔符
要做到这一点,您可以使用。你可以
分解数组,但这并不理想,因为数组输出取决于
区域设置:
{//示例1
设f=new Intl.DateTimeFormat('en');
设a=f.formatoparts();
控制台日志(a);
}
{//示例2
设f=new Intl.DateTimeFormat('hi');
设a=f.formatoparts();
控制台日志(a);
}
使用:
返回:
Saturday, June 9th, 2007, 5:46:21 PM
我认为您可以使用非标准的
日期方法
formatString:与C中函数所期望的格式相同的格式字符串
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
参考文献:
moment().format('YYYY-MM-DD HH:m:s'); // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 11 hours ago
moment().endOf('day').fromNow(); // in 13 hours
var today = new Date().toISOString().slice(0, 10);
请记住,上述解决方案不考虑您的时区偏移
你可以考虑使用这个函数:< /P>
function toJSONLocal (date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
这将为您提供正确的日期,以防您在一天的开始/结束时执行此代码
- 例如:
Date.create().format('{Weekday} {Month} {dd}, {yyyy}');
Date.create().format('{12hr}:{mm}{tt}')
下面是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式设置。它模仿PHP的日期格式化功能来满足我的需要。可以随意使用它,它只是扩展了已经存在的Date()对象。这可能不是最优雅的解决方案,但它符合我的需要
var d = new Date();
d_string = d.format("m/d/Y h:i:s");
/**************************************
* Date class extension
*
*/
// Provide month names
Date.prototype.getMonthName = function(){
var month_names = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
return month_names[this.getMonth()];
}
// Provide month abbreviation
Date.prototype.getMonthAbbr = function(){
var month_abbrs = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
return month_abbrs[this.getMonth()];
}
// Provide full day of week name
Date.prototype.getDayFull = function(){
var days_full = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
return days_full[this.getDay()];
};
// Provide full day of week name
Date.prototype.getDayAbbr = function(){
var days_abbr = [
'Sun',
'Mon',
'Tue',
'Wed',
'Thur',
'Fri',
'Sat'
];
return days_abbr[this.getDay()];
};
// Provide the day of year 1-365
Date.prototype.getDayOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
};
// Provide the day suffix (st,nd,rd,th)
Date.prototype.getDaySuffix = function() {
var d = this.getDate();
var sfx = ["th","st","nd","rd"];
var val = d%100;
return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
};
// Provide Week of Year
Date.prototype.getWeekOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
// Provide if it is a leap year or not
Date.prototype.isLeapYear = function(){
var yr = this.getFullYear();
if ((parseInt(yr)%4) == 0){
if (parseInt(yr)%100 == 0){
if (parseInt(yr)%400 != 0){
return false;
}
if (parseInt(yr)%400 == 0){
return true;
}
}
if (parseInt(yr)%100 != 0){
return true;
}
}
if ((parseInt(yr)%4) != 0){
return false;
}
};
// Provide Number of Days in a given month
Date.prototype.getMonthDayCount = function() {
var month_day_counts = [
31,
this.isLeapYear() ? 29 : 28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
return month_day_counts[this.getMonth()];
}
// format provided date into this.format format
Date.prototype.format = function(dateFormat){
// break apart format string into array of characters
dateFormat = dateFormat.split("");
var date = this.getDate(),
month = this.getMonth(),
hours = this.getHours(),
minutes = this.getMinutes(),
seconds = this.getSeconds();
// get all date properties ( based on PHP date object functionality )
var date_props = {
d: date < 10 ? '0'+date : date,
D: this.getDayAbbr(),
j: this.getDate(),
l: this.getDayFull(),
S: this.getDaySuffix(),
w: this.getDay(),
z: this.getDayOfYear(),
W: this.getWeekOfYear(),
F: this.getMonthName(),
m: month < 10 ? '0'+(month+1) : month+1,
M: this.getMonthAbbr(),
n: month+1,
t: this.getMonthDayCount(),
L: this.isLeapYear() ? '1' : '0',
Y: this.getFullYear(),
y: this.getFullYear()+''.substring(2,4),
a: hours > 12 ? 'pm' : 'am',
A: hours > 12 ? 'PM' : 'AM',
g: hours % 12 > 0 ? hours % 12 : 12,
G: hours > 0 ? hours : "12",
h: hours % 12 > 0 ? hours % 12 : 12,
H: hours,
i: minutes < 10 ? '0' + minutes : minutes,
s: seconds < 10 ? '0' + seconds : seconds
};
// loop through format array of characters and add matching data else add the format character (:,/, etc.)
var date_string = "";
for(var i=0;i<dateFormat.length;i++){
var f = dateFormat[i];
if(f.match(/[a-zA-Z]/g)){
date_string += date_props[f] ? date_props[f] : '';
} else {
date_string += f;
}
}
return date_string;
};
/*
*
* END - Date class extension
*
************************************/
var d=新日期();
d_string=d.format(“m/d/Y h:i:s”);
/**************************************
*日期类扩展
*
*/
//提供月份名称
Date.prototype.getMonthName=函数(){
变量月份名称=[
“一月”,
“二月”,
“三月”,
"四月",,
“五月”,
“六月”,
“七月”,
“八月”,
"九月",,
“十月”,
"十一月",,
“十二月”
];
返回月份名称[this.getMonth()];
}
//提供月份缩写
Date.prototype.getMonthAbbr=函数(){
变量月_缩写=[
“一月”,
二月,,
“三月”,
“四月”,
“五月”,
"六月",,
七月,,
"八月",,
"九月",,
“十月”,
十一月,,
“十二月”
];
返回月份\缩写[this.getMonth()];
}
//提供一周中的全天名称
Date.prototype.getDayFull=函数(){
变量天数\u满=[
"星期日",,
“星期一”,
"星期二",,
“星期三”,
"星期四",,
“星期五”,
“星期六”
];
返回天数已满[this.getDay()];
};
//提供一周中的全天名称
Date.prototype.getDayAbbr=函数(){
var days_缩写=[
"太阳",,
“周一”,
“星期二”,
“Wed”,
“星期四”,
“星期五”,
“Sat”
];
返回天数\u缩写[this.getDay()];
};
//提供1-365年的日期
Date.prototype.getDayOfYear=函数(){
var onejan=新日期(this.getFullYear(),0,1);
返回Math.ceil((this-onejan)/86400000);
};
//提供日期后缀(st、nd、rd、th)
Date.prototype.getDaySuffix=函数(){
var d=this.getDate();
var sfx=[“th”、“st”、“nd”、“rd”];
var val=d%100;
返回(sfx[(val-20)%10]| | sfx[val]| | sfx[0]);
};
//提供一年中的一周
Date.prototype.getWeekOfYear=函数(){
var onejan=新日期(this.getFullYear(),0,1);
返回Math.ceil(((this-onejan)/86400000)+onejan.getDay()+1)/7);
}
//提供是否为闰年
Date.prototype.isLeapYear=函数(){
var yr=this.getFullYear();
如果((parseInt(yr)%4)==0){
如果(parseInt(yr)%100==0){
如果(parseInt(yr)%400!=0){
返回false;
}
如果(parseInt(yr)%400==0){
返回true;
}
}
如果(parseInt(yr)%100!=0){
返回true;
}
}
如果((parseInt(yr)%4)!=0){
返回false;
}
};
//提供给定月份的天数
Date.prototype.getMonthDayCount=函数(){
变量月日计数=[
31,
这个.isLeapYear()?29:28,
31,
30,
31,
30,
31,
31,
var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));
// formatted will be 'Jul 8, 2014'
var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
const date = new Date(Date.UTC(2020, 4, 2, 3, 23, 16, 738));
const fmt = (dt, lc = "en-US") => (str, ...expr) =>
str.map((str, i) => str + (expr[i]?dt.toLocaleDateString(lc, expr[i]) :'')).join('')
console.log(fmt(date)`${{year: 'numeric'}}-${{month: '2-digit'}}-${{day: '2-digit'}}`);
// expected output: "2020-05-02"
var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);
moment().format('YYYY-MM-DD HH:m:s'); // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 11 hours ago
moment().endOf('day').fromNow(); // in 13 hours
var d = new Date();
var datestring = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();
// 16-5-2015 9:50
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
// 16-05-2015 09:50
var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
'24-Jan-2016'
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var Days = [
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
];
var formatDate = function(dt,format){
format = format.replace('ss', pad(dt.getSeconds(),2));
format = format.replace('s', dt.getSeconds());
format = format.replace('dd', pad(dt.getDate(),2));
format = format.replace('d', dt.getDate());
format = format.replace('mm', pad(dt.getMinutes(),2));
format = format.replace('m', dt.getMinutes());
format = format.replace('MMMM', monthNames[dt.getMonth()]);
format = format.replace('MMM', monthNames[dt.getMonth()].substring(0,3));
format = format.replace('MM', pad(dt.getMonth()+1,2));
format = format.replace(/M(?![ao])/, dt.getMonth()+1);
format = format.replace('DD', Days[dt.getDay()]);
format = format.replace(/D(?!e)/, Days[dt.getDay()].substring(0,3));
format = format.replace('yyyy', dt.getFullYear());
format = format.replace('YYYY', dt.getFullYear());
format = format.replace('yy', (dt.getFullYear()+"").substring(2));
format = format.replace('YY', (dt.getFullYear()+"").substring(2));
format = format.replace('HH', pad(dt.getHours(),2));
format = format.replace('H', dt.getHours());
return format;
}
pad = function(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
var date = '10/8/2010';
date = new Date(date);
date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010"
date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010"
date = new Intl.DateTimeFormat('ar-EG').format(date); // Arabic date format: "٨/١٠/٢٠١٠"
date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');
"10-Aug-2010"
let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));
new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])
nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".
weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
var date = new Date();
console.log(date.toLocaleDateString("en-US", { day: 'numeric' })
+ "-"+ date.toLocaleDateString("en-US", { month: 'short' })
+ "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> 16-Nov-2019
console.log(date.toLocaleDateString("en-US", { month: 'long' })
+ " " + date.toLocaleDateString("en-US", { day: 'numeric' })
+ ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> November 16, 2019
const formattedDate = new Date().toDateString()
// The above yields e.g. 'Mon Jan 06 2020'
const [, month, day, year] = formattedDate.split(' ')
const ddMmmYyyy = `${day}-${month}-${year}`
// or
const ddMmmYyyy = [day, month, year].join('-')