use*_*547 293 javascript formatting date date-format time-format
大家好我有一个日期格式太阳5月11,2014我怎么能在javascript中将它转换为2014-05-11.
function taskDate(dateMilli) {
var d = (new Date(dateMilli) + '').split(' ');
d[2] = d[2] + ',';
return [d[0], d[1], d[2], d[3]].join(' ');
}
var datemilli = Date.parse('Sun May 11,2014');
taskdate(datemilli);
Run Code Online (Sandbox Code Playgroud)
上面的代码给了我相同的日期格式太阳可能11,2014请帮忙
use*_*953 412
你可以做
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
Run Code Online (Sandbox Code Playgroud)
用法示例:
alert(formatDate('Sun May 11,2014'));
Run Code Online (Sandbox Code Playgroud)
输出:
2014-05-11
Run Code Online (Sandbox Code Playgroud)
小提琴演示:http://jsfiddle.net/abdulrauf6182012/2Frm3/
Dar*_*ous 351
只需利用内置toISOString方法将日期转换为ISO 8601格式.
yourDate.toISOString().split('T')[0]
Run Code Online (Sandbox Code Playgroud)
其中yourDate是您的日期对象.
Jua*_*dez 164
2020 答案
您可以使用本机.toLocaleDateString()函数,该函数支持多个有用的参数,例如语言环境(选择 MM/DD/YYYY 或 YYYY/MM/DD等格式)、时区(转换日期)和格式详细信息选项(例如: 1 对 01 对 1 月)。
例子
const testCases = [
new Date().toLocaleDateString(), // 8/19/2020
new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'}),
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)
]
for (const testData of testCases) {
console.log(testData)
}Run Code Online (Sandbox Code Playgroud)
请注意,有时要以您想要的特定格式输出日期,您必须找到与该格式兼容的语言环境。您可以在此处找到语言环境示例:https : //www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
请注意,语言环境只是更改格式,如果要将特定日期转换为特定国家或城市的等效时间,则需要使用时区参数。
Fer*_*lar 102
我用这种方式获取yyyy-mm-dd格式的日期:)
var todayDate = new Date().toISOString().slice(0,10);
Run Code Online (Sandbox Code Playgroud)
Joh*_*ers 86
将日期转换为yyyy-mm-dd格式的最简单方法是:
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
Run Code Online (Sandbox Code Playgroud)
这个怎么运作 :
new Date("Sun May 11,2014")将字符串"Sun May 11,2014"转换为日期对象,该日期对象表示Sun May 11 2014 00:00:00基于当前区域设置的时区中的时间(主机系统设置)new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))Sun May 11 2014 00:00:00通过减去时区偏移量,将您的日期转换为与UTC时间(标准时间)对应的日期对象.toISOString() 将日期对象转换为ISO 8601字符串 2014-05-11T00:00:00.000Z.split("T") 将字符串拆分为数组 ["2014-05-11", "00:00:00.000Z"][0] 获取该数组的第一个元素var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
console.log(dateString);Run Code Online (Sandbox Code Playgroud)
小智 30
format = function date2str(x, y) {
var z = {
M: x.getMonth() + 1,
d: x.getDate(),
h: x.getHours(),
m: x.getMinutes(),
s: x.getSeconds()
};
y = y.replace(/(M+|d+|h+|m+|s+)/g, function(v) {
return ((v.length > 1 ? "0" : "") + eval('z.' + v.slice(-1))).slice(-2)
});
return y.replace(/(y+)/g, function(v) {
return x.getFullYear().toString().slice(-v.length)
});
}
Run Code Online (Sandbox Code Playgroud)
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
Run Code Online (Sandbox Code Playgroud)
Hen*_*Jan 27
2021 年的解决方案使用Intl.
Intl现在所有浏览器都支持新对象。
您可以通过选择使用所需格式的“区域设置”来选择格式。
瑞典语言环境使用格式“yyyy-mm-dd”:
// Create a date
const date = new Date(2021, 10, 28);
// Create a formatter using the "sv-SE" locale
const dateFormatter = Intl.DateTimeFormat('sv-SE');
// Use the formatter to format the date
console.log(dateFormatter.format(date)); // "2021-11-28"
Run Code Online (Sandbox Code Playgroud)
使用 Intl 的缺点:
Ale*_*gin 26
您可以toLocaleDateString('fr-CA')在Date对象上使用
console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));Run Code Online (Sandbox Code Playgroud)
我还发现这些语言环境从这个语言环境列表中给出了正确的结果所有语言环境及其短代码的列表?
'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'
Run Code Online (Sandbox Code Playgroud)
'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'
Run Code Online (Sandbox Code Playgroud)
Luc*_* C. 21
在大多数情况下(没有时区处理)这就足够了:
date.toISOString().substring(0,10)
Run Code Online (Sandbox Code Playgroud)
例子
var date = new Date();
console.log(date.toISOString()); // 2022-07-04T07:14:08.925Z
console.log(date.toISOString().substring(0,10)); // 2022-07-04
Run Code Online (Sandbox Code Playgroud)
aqw*_*sez 20
一些答案的组合:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');
Run Code Online (Sandbox Code Playgroud)
Kam*_*ski 17
.toJSON().slice(0,10);
Run Code Online (Sandbox Code Playgroud)
.toJSON().slice(0,10);
Run Code Online (Sandbox Code Playgroud)
Luo*_*Hui 13
检索年、月和日,然后将它们放在一起。直接、简单、准确。
function formatDate(date) {
var year = date.getFullYear().toString();
var month = (date.getMonth() + 101).toString().substring(1);
var day = (date.getDate() + 100).toString().substring(1);
return year + "-" + month + "-" + day;
}
//Usage example:
alert(formatDate(new Date()));Run Code Online (Sandbox Code Playgroud)
Nif*_*Ojo 10
如果您不反对使用任何库,则可以使用Moments.js库,如下所示:
var now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:mm:ss');Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>Run Code Online (Sandbox Code Playgroud)
只需使用以下命令:
var date = new Date('1970-01-01'); // Or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
Run Code Online (Sandbox Code Playgroud)
简单而甜美;)
小智 9
toISOString()假设您的日期是本地时间并将其转换为UTC.您将收到不正确的日期字符串.
以下方法应该返回您需要的内容.
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};
Run Code Online (Sandbox Code Playgroud)
资料来源:https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
小智 8
不幸的是,JavaScript 的Date对象有很多缺陷。任何基于Date\ 内置的toISOString解决方案都必须扰乱时区,正如该问题的其他一些答案中所讨论的那样。Temporal.PlainDate提案中Temporal给出了表示 ISO-8601 日期(不带时间)的干净解决方案。自 2021 年 2 月起,您必须选择最适合您的解决方法。
Date与普通字符串连接一起使用假设您的内部表示基于Date,您可以执行手动字符串连接。下面的代码避免了一些Date\ 的陷阱(时区、从零开始的月份、缺少 2 位数字格式),但可能还有其他问题。
function vanillaToDateOnlyIso8601() {\n // month May has zero-based index 4\n const date = new Date(2014, 4, 11);\n\n const yyyy = date.getFullYear();\n const mm = String(date.getMonth() + 1).padStart(2, "0"); // month is zero-based\n const dd = String(date.getDate()).padStart(2, "0");\n\n if (yyyy < 1583) {\n // TODO: decide how to support dates before 1583\n throw new Error(`dates before year 1583 are not supported`);\n }\n\n const formatted = `${yyyy}-${mm}-${dd}`;\n console.log("vanilla", formatted);\n}\nRun Code Online (Sandbox Code Playgroud)\nDate与辅助库一起使用(例如formatISO来自date-fns)这是一种流行的方法,但您仍然被迫将日历日期处理为Date,它代表
\n\n独立于平台的格式的单个时刻
\n
不过,以下代码应该可以完成工作:
\nimport { formatISO } from "date-fns";\n\nfunction dateFnsToDateOnlyIso8601() {\n // month May has zero-based index 4\n const date = new Date(2014, 4, 11);\n const formatted = formatISO(date, { representation: "date" });\n console.log("date-fns", formatted);\n}\nRun Code Online (Sandbox Code Playgroud)\n我希望有一个干净且经过实战检验的库,可以带来自己精心设计的 date\xe2\x80\x93time 表示形式。此问题中的任务的一个有希望的候选者来自LocalDate,@js-joda/core但该库的活跃度不如 ,例如date-fns。在使用一些示例代码时,我在添加可选的@js-joda/timezone.
然而,核心功能有效并且对我来说看起来非常干净:
\nimport { LocalDate, Month } from "@js-joda/core";\n\nfunction jodaDateOnlyIso8601() {\n const someDay = LocalDate.of(2014, Month.MAY, 11);\n const formatted = someDay.toString();\n console.log("joda", formatted);\n}\nRun Code Online (Sandbox Code Playgroud)\nTemporal-proposal polyfill进行实验不建议在生产环境中这样做,但如果您愿意,可以导入 future:
\nimport { Temporal } from "proposal-temporal";\n\nfunction temporalDateOnlyIso8601() {\n // yep, month is one-based here (as of Feb 2021)\n const plainDate = new Temporal.PlainDate(2014, 5, 11);\n const formatted = plainDate.toString();\n console.log("proposal-temporal", formatted);\n}\nRun Code Online (Sandbox Code Playgroud)\n
只需检索年、月、日,然后将它们放在一起即可。
function dateFormat(date) {
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${year}-${month}-${day}`;
}
console.log(dateFormat(new Date()));Run Code Online (Sandbox Code Playgroud)
小智 6
你可以试试这个:https : //www.npmjs.com/package/timesolver
npm i timesolver
Run Code Online (Sandbox Code Playgroud)
在您的代码中使用它:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");
Run Code Online (Sandbox Code Playgroud)
您可以使用此方法获取日期字符串:
getString
Run Code Online (Sandbox Code Playgroud)
还要考虑时区,这个单行应该没有任何库:
new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
Run Code Online (Sandbox Code Playgroud)
当 ES2018 出现时(在 chrome 中工作),您可以简单地对其进行正则表达式
(new Date())
.toISOString()
.replace(
/^(?<year>\d+)-(?<month>\d+)-(?<day>\d+)T.*$/,
'$<year>-$<month>-$<day>'
)
Run Code Online (Sandbox Code Playgroud)
2020-07-14
或者如果你想要一些没有任何库的非常通用的东西
(new Date())
.toISOString()
.match(
/^(?<yyyy>\d\d(?<yy>\d\d))-(?<mm>0?(?<m>\d+))-(?<dd>0?(?<d>\d+))T(?<HH>0?(?<H>\d+)):(?<MM>0?(?<M>\d+)):(?<SSS>(?<SS>0?(?<S>\d+))\.\d+)(?<timezone>[A-Z][\dA-Z.-:]*)$/
)
.groups
Run Code Online (Sandbox Code Playgroud)
这导致提取以下内容
{
H: "8"
HH: "08"
M: "45"
MM: "45"
S: "42"
SS: "42"
SSS: "42.855"
d: "14"
dd: "14"
m: "7"
mm: "07"
timezone: "Z"
yy: "20"
yyyy: "2020"
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用replace(..., '$<d>/$<m>/\'$<yy> @ $<H>:$<MM>')as 在顶部而不是.match(...).groups获取
14/7/'20 @ 8:45
Run Code Online (Sandbox Code Playgroud)
const formatDate = d => [
d.getFullYear(),
(d.getMonth() + 1).toString().padStart(2, '0'),
d.getDate().toString().padStart(2, '0')
].join('-');
Run Code Online (Sandbox Code Playgroud)
您可以使用padstart。
padStart(n, '0') 确保字符串中至少有 n 个字符,并在它前面加上 '0' 直到达到该长度。
join('-') 连接一个数组,在每个元素之间添加 '-' 符号。
getMonth() 从 0 开始,因此是 +1。
这就是我所做的。
另一种替代的简短方法:-
const date = new Date().toISOString();
console.log(date.substring(0, date.indexOf('T')));Run Code Online (Sandbox Code Playgroud)
substring()与 一起使用indexOf("T"),而不是在字符“T”处将其拆分为数组并访问第 0 个索引处的元素。
这是一种方法:
var date = Date.parse('Sun May 11,2014');
function format(date) {
date = new Date(date);
var day = ('0' + date.getDate()).slice(-2);
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var year = date.getFullYear();
return year + '-' + month + '-' + day;
}
console.log(format(date));
Run Code Online (Sandbox Code Playgroud)
我建议使用类似formatDate-js 的东西,而不是每次都尝试复制它。只需使用支持所有主要 strftime 操作的库即可。
new Date().format("%Y-%m-%d")
Run Code Online (Sandbox Code Playgroud)
new Date().toLocaleDateString('pt-br').split( '/' ).reverse( ).join( '-' );
Run Code Online (Sandbox Code Playgroud)
或者
new Date().toISOString().split('T')[0]
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString()
new Date('23/03/2020'.split('/').reverse().join('-')).toISOString().split('T')[0]
Run Code Online (Sandbox Code Playgroud)
尝试这个!
警告此代码在某些版本的 Chrome、Node.js 等中不起作用。
\nyyyy-MM-ddM/d/yyyy参考
\n转换Date为日期字符串时请考虑时区。
可以使用两种方法。
\n.toISOString();- 固定为 GMT+0。包括时间,稍后应将其删除。.toLocaleDateString(\'en-CA\');- 可以指定时区。默认为系统。请注意,这en-CA是一个区域设置,而不是一个时区。加拿大使用该YYYY-MM-DD格式。
在以下示例中,系统时区设置为 PDT (GMT-7)
\nconst date = new Date(\'2023-04-08 GMT+09:00\');\n// Sat Apr 08 2023 00:00:00 GMT+0900 (\xed\x95\x9c\xea\xb5\xad \xed\x91\x9c\xec\xa4\x80\xec\x8b\x9c)\n// Fri Apr 07 2023 08:00:00 GMT-0700 (Pacific Daylight Time)\n\n// Based on GMT+0 or UTC - time is substringed.\ndate.toISOString(); // \'2023-04-07T15:00:00.000Z\'\ndate.toISOString().substring(0, 10); // \'2023-04-07\'\n\n// Based on GMT-7 - local timezone of the system\ndate.toLocaleDateString(\'en-CA\'); // \'2023-04-07\'\n\n// Based on GMT+9 - Asia/Seoul is GMT+9\ndate.toLocaleDateString(\'en-CA\', { timeZone: \'Asia/Seoul\' }); // \'2023-04-08\'\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
712306 次 |
| 最近记录: |