大家好我有一个日期格式太阳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);
上面的代码给了我相同的日期格式太阳可能11,2014请帮忙
你可以做
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('-');
}
用法示例:
alert(formatDate('Sun May 11,2014'));
输出:
2014-05-11
我建议使用像https://github.com/brightbits/formatDate-js这样的东西,而不是每次都尝试复制它,只需使用支持所有主要strftime动作的库。
new Date().format("%Y-%m-%d")
你可以试试这个:https://www.npmjs.com/package/timesolver
npm i timesolver
在你的代码中使用它:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");
您可以使用此方法获取日期字符串:
的getString
希望对你有帮助!
这些答案都没有让我满意。我想要一个跨平台的解决方案,让我在当地时区度过一天而不使用任何外部库。
这就是我想出的:
function localDay(time) {
var minutesOffset = time.getTimezoneOffset()
var millisecondsOffset = minutesOffset*60*1000
var local = new Date(time - millisecondsOffset)
return local.toISOString().substr(0, 10)
}
这应该在日期引用的时区中以YYYY-MM-DD格式返回日期的日期。
所以例如localDay(new Date("2017-08-24T03:29:22.099Z"))
将返回"2017-08-23"
,即使它已经是UTC的第24位。
您需要使用polyfill Date.prototype.toISOString才能在IE8中工作,但应该在其他任何地方都支持它。
检索年,月和日,然后将它们放在一起。直接,简单,准确。
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()));
还要考虑时区,这个衬里应该没有任何库:
new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
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));
重新格式化日期字符串非常简单,例如
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));
Date.js非常适合这个。
require("datejs")
(new Date()).toString("yyyy-MM-dd")
这对我有用,可以获得所需格式的当前日期(YYYYMMDD HH:MM:SS
var d = new Date();
var date1=d.getFullYear()+''+((d.getMonth()+1)<10?"0"+(d.getMonth()+1):(d.getMonth()+1))+''+(d.getDate()<10?"0"+d.getDate():d.getDate());
var time1=(d.getHours()<10?"0"+d.getHours():d.getHours())+':'+(d.getMinutes()<10?"0"+d.getMinutes():d.getMinutes())+':'+(d.getSeconds()<10?"0"+d.getSeconds():d.getSeconds());
print(date1+' '+time1);
var d = new Date("Sun May 1,2014");
var year = d.getFullYear();
var month = d.getMonth() + 1;
var day = d.getDate();
month = checkZero(month);
day = checkZero(day);
var date = "";
date += year;
date += "-";
date += month;
date += "-";
date += day;
document.querySelector("#display").innerHTML = date;
function checkZero(i)
{
if (i < 10)
{
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
<div id="display"></div>
只需利用内置的toISOString
方法,使您的日期符合ISO 8601格式。
yourDate.toISOString().split('T')[0]
其中yourDate是您的日期对象。
不需要图书馆
只是纯粹的JavaScript
以下示例从今天起持续两个月
var d = new Date()
d.setMonth(d.getMonth() - 2);
var dateString = new Date(d);
console.log('Before Format', dateString, 'After format', dateString.toISOString().slice(0,10))
这是一个小函数,可以使用与PHP函数date()
相同的参数,并在javascript中返回日期/时间字符串。
请注意,并非所有PHP的date()格式选项都受支持。您可以扩展parts
对象以创建缺少的格式标记
/**
* Date formatter with PHP "date()"-compatible format syntax.
*/
const formatDate = (format, date) => {
if (!format) { format = 'Y-m-d' }
if (!date) { date = new Date() }
const parts = {
Y: date.getFullYear().toString(),
y: ('00' + (date.getYear() - 100)).toString().slice(-2),
m: ('0' + (date.getMonth() + 1)).toString().slice(-2),
n: (date.getMonth() + 1).toString(),
d: ('0' + date.getDate()).toString().slice(-2),
j: date.getDate().toString(),
H: ('0' + date.getHours()).toString().slice(-2),
G: date.getHours().toString(),
i: ('0' + date.getMinutes()).toString().slice(-2),
s: ('0' + date.getSeconds()).toString().slice(-2)
}
const modifiers = Object.keys(parts).join('')
const reDate = new RegExp('(?<!\\\\)[' + modifiers + ']', 'g')
const reEscape = new RegExp('\\\\([' + modifiers + '])', 'g')
return format
.replace(reDate, $0 => parts[$0])
.replace(reEscape, ($0, $1) => $1)
}
// ----- EXAMPLES -----
console.log( formatDate() ); // "2019-05-21"
console.log( formatDate('H:i:s') ); // "16:21:32"
console.log( formatDate('Y-m-d, o\\n H:i:s') ); // "2019-05-21, on 16:21:32"
console.log( formatDate('Y-m-d', new Date(2000000000000)) ); // "2033-05-18"
要旨
这是一个有更新版本的formatDate()
函数和其他示例的要点:https://gist.github.com/stracker-phil/c7b68ea0b1d5bbb97af0a6a3dc66e0d9
这是一种方法:
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));
如果所有时区的日期需要相同,例如表示来自数据库的某些值,那么请确保在js date对象上使用utc版本的day,month,fullyear函数,因为这将在utc时间显示并避免在1中出现错误某些时区。更好的是使用moment.js日期库进行这种格式化
又一个答案的组合。很可读,但有点冗长。
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);
}
我修改了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);
上面的一些是好的 - 但不是很灵活。我想要能够真正处理更多边缘情况的东西,所以我采用了@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;
}
用法示例:
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');
new Date(new Date(YOUR_DATE.toISOString()).getTime() -
(YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)
格式化并从散列图数据中查找最大,最小日期
var obj = {"a":'2001-15-01', "b": '2001-12-02' , "c": '2001-1-03'};
function findMaxMinDate(obj){
let formatEncode = (id)=> { let s = id.split('-'); return `${s[0]+'-'+s[2]+'-'+s[1]}`}
let formatDecode = (id)=> { let s = id.split('/'); return `${s[2]+'-'+s[0]+'-'+s[1]}`}
let arr = Object.keys( obj ).map(( key )=> { return new Date(formatEncode(obj[key])); });
let min = new Date(Math.min.apply( null, arr )).toLocaleDateString();
let max = new Date(Math.max.apply( null, arr )).toLocaleDateString();
return {maxd: `${formatDecode(max)}`, mind:`${formatDecode(min)}`}
}
console.log(findMaxMinDate(obj));
所有给出的答案都很棒并帮助了我。在我的情况下,我想以yyyy mm dd格式和date-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);
我用这种方式获取yyyy-mm-dd格式的日期:)
var todayDate = new Date().toISOString().slice(0,10);
通过我的date-shortcode包装轻松完成:
const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
//=> '2014-05-11'
将日期转换为yyyy-mm-dd格式的最简单方法是:
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
这个怎么运作 :
new Date("Sun May 11,2014")
将字符串"Sun May 11,2014"
转换为日期对象,该日期对象根据当前区域设置(主机系统设置)在时区中表示时间Sun May 11 2014 00:00:00
new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
通过减去时区偏移量将您的日期转换为与UTC(标准时间)中的时间Sun May 11 2014 00:00:00
对应的日期对象.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);
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)
});
}
format(new Date('Sun May 11,2014'), 'yyyy-MM-dd')
"2014-05-11
一些答案的组合:
var d = new Date(date);
date = [
d.getFullYear(),
('0' + (d.getMonth() + 1)).slice(-2),
('0' + d.getDate()).slice(-2)
].join('-');
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]);
};
资料来源:https://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
如果你没有任何反对使用库的东西;你可以像这样使用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');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
为什么不简单地使用它
var date = new Date('1970-01-01'); //or your date here
console.log((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear());
简单而甜蜜;)