Hi all i have a Date format Sun May 11,2014 how can i convert it to 2014-05-11 in javascript.
你好,我有一个日期格式,2014年5月11日,我怎么能把它转换成2014-05-11的javascript。
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);
the above code gives me same date format sun may 11,2014 please help
以上代码为我提供了2014年5月11日的日期格式,请帮忙。
24 个解决方案
#1
175
you can do
你可以做
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('-');
}
usage example:
使用的例子:
alert(formatDate('Sun May 11,2014'));
Output:
输出:
2014-05-11
Demo on fiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/
演示在小提琴:http://jsfiddle.net/abdulrauf6182012/2Frm3/
#2
131
Just leverage the built in toISOString
method that brings your date to ISO 8601 format.
只要利用toISOString方法的构建,将您的日期引入ISO 8601格式。
yourDate.toISOString().split('T')[0]
where yourDate is your date object.
你的约会对象就是你的约会对象。
#3
46
I use this way to get the date in format yyyy-mm-dd :)
我用这种方法得到了yyyy-mm-dd格式的日期:
var todayDate = new Date().toISOString().slice(0,10);
#4
21
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)
});
}
result:
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
#5
4
A combination of some of the answers:
一些答案的组合:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');
#6
4
toISOString()
assumes your date is local time and converts it to UTC. You will get incorrect date string.
toISOString()假设您的日期是本地时间,并将其转换为UTC。您将得到不正确的日期字符串。
The following method should return what you need.
下面的方法应该返回您所需要的。
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]);
};
Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
来源:https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
#7
3
I suggest using something like this https://github.com/brightbits/formatDate-js instead of trying to replicate it every time, just use a library that supports all the major strftime actions.
我建议使用像这样的https://github.com/brightbits/formatDate-js,而不是每次都尝试复制它,只要使用一个支持所有主要strftime操作的库即可。
new Date().format("%Y-%m-%d")
#8
3
Why not simply use this
为什么不直接使用它呢?
var date = new Date('1970-01-01'); //or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
Simple and sweet ;)
简单和甜蜜;
#9
1
function myYmd(D){
var pad = function(num) {
var s = '0' + num;
return s.substr(s.length - 2);
}
var Result = D.getFullYear() + '-' + pad((D.getMonth() + 1)) + '-' + pad(D.getDate());
return Result;
}
var datemilli = new Date('Sun May 11,2014');
document.write(myYmd(datemilli));
#10
1
None of these answers quite satisfied me. I wanted a cross platform solution that gives me the day in the local timezone without using any external libraries.
这些回答我都不满意。我想要一个跨平台的解决方案,在不使用任何外部库的情况下,在本地时区中提供一天的时间。
This is what I came up with:
这就是我想到的:
function localDay(time) {
var minutesOffset = time.getTimezoneOffset()
var millisecondsOffset = minutesOffset*60*1000
var local = new Date(time - millisecondsOffset)
return local.toISOString().substr(0, 10)
}
That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.
这应该以yyy - mm - dd格式返回日期的日期,在timezone中日期引用。
So for example localDay(new Date("2017-08-24T03:29:22.099Z"))
will return "2017-08-23"
even though it's already the 24th at UTC.
因此,例如localDay(new Date(“2017-08-24T03:29:22.099Z”))将返回“2017-08-23”,尽管它已经是UTC的第24个日期了。
You'll need to polyfill Date.prototype.toISOString for it to work in IE8, but it should be supported everywhere else.
您将需要填充数据。原型。toISOString在IE8中工作,但在其他任何地方都应该得到支持。
#11
1
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;
}
alert(formatDate(new Date()));
#12
0
Here is one way to do it:
这里有一个方法:
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));
#13
0
If the date needs to be same across all timezones for example represents some value from database then be sure to use utc versions of the day, month, fullyear functions on js date object as this will display in utc time and avoid off by 1 errors in certain time zones. Even better use moment.js date library for this sort of formatting
如果相同日期需要在所有时区例如代表一个值从数据库然后一定要使用utc版本的天,月,fullyear函数js约会的对象将显示在utc时间,避免了在特定时区1错误。更好的使用时间。js date库用于这种格式。
#14
0
you can try this: timeSolver.js
你可以试试这个:timeSolver.js。
var date = new Date();
var dateString = timeSolver.getString(date, "YYYY-MM-DD");
You can get date string by using this method:
您可以使用此方法获取日期字符串:
getString
getString
Hope this will help you!
希望这对你有帮助!
#15
0
Reformatting a date string is fairly straight forward, e.g.
重新格式化日期字符串是相当直接的。
var s = 'Sun May 11,2014';
function reformatDate(s) {
function z(n){return ('0' + n).slice(-2)}
var months = [,'jan','feb','mar','apr','may','jun',
'jul','aug','sep','oct','nov','dec'];
var b = s.split(/\W+/);
return b[3] + '-' +
z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +
z(b[2]);
}
console.log(reformatDate(s));
#16
0
Yet another combination of the answers. Nicely readable, but a little lengthy.
这是答案的另一个组合。可读性很好,但有点冗长。
function getCurrentDayTimestamp() {
const d = new Date();
return new Date(
Date.UTC(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds()
)
// `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
// and we want the first part ("2017-08-22")
).toISOString().slice(0, 10);
}
#17
0
I modified Samit Satpute's response as follows:
我修改了Samit Satpute的响应如下:
var newstartDate = new Date();
// newstartDate.setDate(newstartDate.getDate() - 1);
var startDate = newstartDate.toISOString().replace(/[-T:\.Z]/g, ""); //.slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format
console.log(startDate);
#18
0
Date.js is great for this.
日期。js很适合这个。
require("datejs")
(new Date()).toString("yyyy-MM-dd")
#19
0
All given answers are great and helped me big. In my situation, I wanted to get the current date in yyyy mm dd format along with date-1. Here is what worked for me.
所有的答案都是伟大的,帮助了我。在我的情况下,我想用yyyymm dd格式的当前日期和日期1。这就是我的工作。
var endDate = new Date().toISOString().slice(0, 10); // To get the Current Date in YYYY MM DD Format
var newstartDate = new Date();
newstartDate.setDate(newstartDate.getDate() - 1);
var startDate = newstartDate.toISOString().slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format
alert(startDate);
#20
0
Easily accomplished by my date-shortcode package:
轻松完成我的日期-短代码包:
const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
//=> '2014-05-11'
#21
0
A few of these above were ok - but weren't very flexible. I wanted something that could really handle more edge cases, so I took @orangleliu 's answer and expanded on it. https://jsfiddle.net/8904cmLd/1/
上面的一些是可以的,但不是很灵活。我想要一些能处理更多边缘情况的东西,所以我用了@orangleliu的答案,并在上面进行了扩展。https://jsfiddle.net/8904cmLd/1/
function DateToString(inDate, formatString) {
// Written by m1m1k 2018-04-05
// Validate that we're working with a date
if(!isValidDate(inDate))
{
inDate = new Date(inDate);
}
// see the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014','USA');
//formatString = CountryCodeToDateFormat(formatString);
var dateObject = {
M: inDate.getMonth() + 1,
d: inDate.getDate(),
D: inDate.getDate(),
h: inDate.getHours(),
m: inDate.getMinutes(),
s: inDate.getSeconds(),
y: inDate.getFullYear(),
Y: inDate.getFullYear()
};
// Build Regex Dynamically based on the list above.
// Should end up with something like this "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
var dateMatchRegex = joinObj(dateObject, "+|") + "+";
var regEx = new RegExp(dateMatchRegex,"g");
formatString = formatString.replace(regEx, function(formatToken) {
var datePartValue = dateObject[formatToken.slice(-1)];
var tokenLength = formatToken.length;
// A conflict exists between specifying 'd' for no zero pad -> expand to '10' and specifying yy for just two year digits '01' instead of '2001'. One expands, the other contracts.
// so Constrict Years but Expand All Else
if(formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
{
// Expand single digit format token 'd' to multi digit value '10' when needed
var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
}
var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
return (zeroPad + datePartValue).slice(-tokenLength);
});
return formatString;
}
Example usage:
使用示例:
DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
#22
-1
String.padStart
makes it easy:
字符串。padStart方便:
var dateObj = new Date();
var dateStr = dateObj.getFullYear() + "-" + String(dateObj.getMonth() + 1).padStart(2, "0") + "-" + String(dateObj.getDate()).padStart(2, "0");
#23
-2
This worked for me, and you can paste this directly into your HTML if needed for testing:
这对我很有效,如果需要测试,您可以直接将其粘贴到HTML中:
<script type="text/javascript">
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($){ //on document.ready
$('#Date').datepicker({
dateFormat: 'yy-mm-dd', // THIS IS THE IMPORTANT PART!!!
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
minDate: '2016-10-19',
maxDate: '2016-11-03'
});
})
}
</script>
#24
-4
Just Use Like this Definatly Working for YYYY MM DD like as (2017-03-12)
像这样使用YYYY MM DD (2017-03-12)
var todayDate = new Date().slice(0,10);
var todayDate = new Date().slice(0,10);
#1
175
you can do
你可以做
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('-');
}
usage example:
使用的例子:
alert(formatDate('Sun May 11,2014'));
Output:
输出:
2014-05-11
Demo on fiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/
演示在小提琴:http://jsfiddle.net/abdulrauf6182012/2Frm3/
#2
131
Just leverage the built in toISOString
method that brings your date to ISO 8601 format.
只要利用toISOString方法的构建,将您的日期引入ISO 8601格式。
yourDate.toISOString().split('T')[0]
where yourDate is your date object.
你的约会对象就是你的约会对象。
#3
46
I use this way to get the date in format yyyy-mm-dd :)
我用这种方法得到了yyyy-mm-dd格式的日期:
var todayDate = new Date().toISOString().slice(0,10);
#4
21
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)
});
}
result:
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
#5
4
A combination of some of the answers:
一些答案的组合:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');
#6
4
toISOString()
assumes your date is local time and converts it to UTC. You will get incorrect date string.
toISOString()假设您的日期是本地时间,并将其转换为UTC。您将得到不正确的日期字符串。
The following method should return what you need.
下面的方法应该返回您所需要的。
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]);
};
Source: https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
来源:https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
#7
3
I suggest using something like this https://github.com/brightbits/formatDate-js instead of trying to replicate it every time, just use a library that supports all the major strftime actions.
我建议使用像这样的https://github.com/brightbits/formatDate-js,而不是每次都尝试复制它,只要使用一个支持所有主要strftime操作的库即可。
new Date().format("%Y-%m-%d")
#8
3
Why not simply use this
为什么不直接使用它呢?
var date = new Date('1970-01-01'); //or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
Simple and sweet ;)
简单和甜蜜;
#9
1
function myYmd(D){
var pad = function(num) {
var s = '0' + num;
return s.substr(s.length - 2);
}
var Result = D.getFullYear() + '-' + pad((D.getMonth() + 1)) + '-' + pad(D.getDate());
return Result;
}
var datemilli = new Date('Sun May 11,2014');
document.write(myYmd(datemilli));
#10
1
None of these answers quite satisfied me. I wanted a cross platform solution that gives me the day in the local timezone without using any external libraries.
这些回答我都不满意。我想要一个跨平台的解决方案,在不使用任何外部库的情况下,在本地时区中提供一天的时间。
This is what I came up with:
这就是我想到的:
function localDay(time) {
var minutesOffset = time.getTimezoneOffset()
var millisecondsOffset = minutesOffset*60*1000
var local = new Date(time - millisecondsOffset)
return local.toISOString().substr(0, 10)
}
That should return the day of the date, in YYYY-MM-DD format, in the timezone the date references.
这应该以yyy - mm - dd格式返回日期的日期,在timezone中日期引用。
So for example localDay(new Date("2017-08-24T03:29:22.099Z"))
will return "2017-08-23"
even though it's already the 24th at UTC.
因此,例如localDay(new Date(“2017-08-24T03:29:22.099Z”))将返回“2017-08-23”,尽管它已经是UTC的第24个日期了。
You'll need to polyfill Date.prototype.toISOString for it to work in IE8, but it should be supported everywhere else.
您将需要填充数据。原型。toISOString在IE8中工作,但在其他任何地方都应该得到支持。
#11
1
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;
}
alert(formatDate(new Date()));
#12
0
Here is one way to do it:
这里有一个方法:
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));
#13
0
If the date needs to be same across all timezones for example represents some value from database then be sure to use utc versions of the day, month, fullyear functions on js date object as this will display in utc time and avoid off by 1 errors in certain time zones. Even better use moment.js date library for this sort of formatting
如果相同日期需要在所有时区例如代表一个值从数据库然后一定要使用utc版本的天,月,fullyear函数js约会的对象将显示在utc时间,避免了在特定时区1错误。更好的使用时间。js date库用于这种格式。
#14
0
you can try this: timeSolver.js
你可以试试这个:timeSolver.js。
var date = new Date();
var dateString = timeSolver.getString(date, "YYYY-MM-DD");
You can get date string by using this method:
您可以使用此方法获取日期字符串:
getString
getString
Hope this will help you!
希望这对你有帮助!
#15
0
Reformatting a date string is fairly straight forward, e.g.
重新格式化日期字符串是相当直接的。
var s = 'Sun May 11,2014';
function reformatDate(s) {
function z(n){return ('0' + n).slice(-2)}
var months = [,'jan','feb','mar','apr','may','jun',
'jul','aug','sep','oct','nov','dec'];
var b = s.split(/\W+/);
return b[3] + '-' +
z(months.indexOf(b[1].substr(0,3).toLowerCase())) + '-' +
z(b[2]);
}
console.log(reformatDate(s));
#16
0
Yet another combination of the answers. Nicely readable, but a little lengthy.
这是答案的另一个组合。可读性很好,但有点冗长。
function getCurrentDayTimestamp() {
const d = new Date();
return new Date(
Date.UTC(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds()
)
// `toIsoString` returns something like "2017-08-22T08:32:32.847Z"
// and we want the first part ("2017-08-22")
).toISOString().slice(0, 10);
}
#17
0
I modified Samit Satpute's response as follows:
我修改了Samit Satpute的响应如下:
var newstartDate = new Date();
// newstartDate.setDate(newstartDate.getDate() - 1);
var startDate = newstartDate.toISOString().replace(/[-T:\.Z]/g, ""); //.slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format
console.log(startDate);
#18
0
Date.js is great for this.
日期。js很适合这个。
require("datejs")
(new Date()).toString("yyyy-MM-dd")
#19
0
All given answers are great and helped me big. In my situation, I wanted to get the current date in yyyy mm dd format along with date-1. Here is what worked for me.
所有的答案都是伟大的,帮助了我。在我的情况下,我想用yyyymm dd格式的当前日期和日期1。这就是我的工作。
var endDate = new Date().toISOString().slice(0, 10); // To get the Current Date in YYYY MM DD Format
var newstartDate = new Date();
newstartDate.setDate(newstartDate.getDate() - 1);
var startDate = newstartDate.toISOString().slice(0, 10); // To get the Yesterday's Date in YYYY MM DD Format
alert(startDate);
#20
0
Easily accomplished by my date-shortcode package:
轻松完成我的日期-短代码包:
const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
//=> '2014-05-11'
#21
0
A few of these above were ok - but weren't very flexible. I wanted something that could really handle more edge cases, so I took @orangleliu 's answer and expanded on it. https://jsfiddle.net/8904cmLd/1/
上面的一些是可以的,但不是很灵活。我想要一些能处理更多边缘情况的东西,所以我用了@orangleliu的答案,并在上面进行了扩展。https://jsfiddle.net/8904cmLd/1/
function DateToString(inDate, formatString) {
// Written by m1m1k 2018-04-05
// Validate that we're working with a date
if(!isValidDate(inDate))
{
inDate = new Date(inDate);
}
// see the jsFiddle for extra code to be able to use DateToString('Sun May 11,2014','USA');
//formatString = CountryCodeToDateFormat(formatString);
var dateObject = {
M: inDate.getMonth() + 1,
d: inDate.getDate(),
D: inDate.getDate(),
h: inDate.getHours(),
m: inDate.getMinutes(),
s: inDate.getSeconds(),
y: inDate.getFullYear(),
Y: inDate.getFullYear()
};
// Build Regex Dynamically based on the list above.
// Should end up with something like this "/([Yy]+|M+|[Dd]+|h+|m+|s+)/g"
var dateMatchRegex = joinObj(dateObject, "+|") + "+";
var regEx = new RegExp(dateMatchRegex,"g");
formatString = formatString.replace(regEx, function(formatToken) {
var datePartValue = dateObject[formatToken.slice(-1)];
var tokenLength = formatToken.length;
// A conflict exists between specifying 'd' for no zero pad -> expand to '10' and specifying yy for just two year digits '01' instead of '2001'. One expands, the other contracts.
// so Constrict Years but Expand All Else
if(formatToken.indexOf('y') < 0 && formatToken.indexOf('Y') < 0)
{
// Expand single digit format token 'd' to multi digit value '10' when needed
var tokenLength = Math.max(formatToken.length, datePartValue.toString().length);
}
var zeroPad = (datePartValue.toString().length < formatToken.length ? "0".repeat(tokenLength) : "");
return (zeroPad + datePartValue).slice(-tokenLength);
});
return formatString;
}
Example usage:
使用示例:
DateToString('Sun May 11,2014', 'MM/DD/yy');
DateToString('Sun May 11,2014', 'yyyy.MM.dd');
DateToString(new Date('Sun Dec 11,2014'),'yy-M-d');
#22
-1
String.padStart
makes it easy:
字符串。padStart方便:
var dateObj = new Date();
var dateStr = dateObj.getFullYear() + "-" + String(dateObj.getMonth() + 1).padStart(2, "0") + "-" + String(dateObj.getDate()).padStart(2, "0");
#23
-2
This worked for me, and you can paste this directly into your HTML if needed for testing:
这对我很有效,如果需要测试,您可以直接将其粘贴到HTML中:
<script type="text/javascript">
if (datefield.type!="date"){ //if browser doesn't support input type="date", initialize date picker widget:
jQuery(function($){ //on document.ready
$('#Date').datepicker({
dateFormat: 'yy-mm-dd', // THIS IS THE IMPORTANT PART!!!
showOtherMonths: true,
selectOtherMonths: true,
changeMonth: true,
minDate: '2016-10-19',
maxDate: '2016-11-03'
});
})
}
</script>
#24
-4
Just Use Like this Definatly Working for YYYY MM DD like as (2017-03-12)
像这样使用YYYY MM DD (2017-03-12)
var todayDate = new Date().slice(0,10);
var todayDate = new Date().slice(0,10);