问题
I have a date with the format Sun May 11,2014
. How can I convert it to 2014-05-11
using 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 code above gives me the same date format, sun may 11,2014
. How can I fix this?
回答1:
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 JSFiddle: http://jsfiddle.net/abdulrauf6182012/2Frm3/
回答2:
Just leverage the built-in toISOString
method that brings your date to the ISO 8601 format:
yourDate.toISOString().split('T')[0]
Where yourDate is your date object.
回答3:
I use this way to get the date in format yyyy-mm-dd :)
var todayDate = new Date().toISOString().slice(0,10);
回答4:
The simplest way to convert your date to the yyyy-mm-dd format, is to do this:
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
How it works:
new Date("Sun May 11,2014")
converts the string"Sun May 11,2014"
to a date object that represents the timeSun May 11 2014 00:00:00
in a timezone based on current locale (host system settings)new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
converts your date to a date object that corresponds with the timeSun May 11 2014 00:00:00
in UTC (standard time) by subtracting the time zone offset.toISOString()
converts the date object to an ISO 8601 string2014-05-11T00:00:00.000Z
.split("T")
splits the string to array["2014-05-11", "00:00:00.000Z"]
[0]
takes the first element of that array
Demo
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
.toISOString()
.split("T")[0];
console.log(dateString);
回答5:
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
回答6:
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('-');
回答7:
If you don't have anything against using libraries, you could just use the Moments.js library like so:
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>
回答8:
toISOString()
assumes your date is local time and converts it to UTC. You will get an incorrect date string.
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/
回答9:
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 ;)
回答10:
I suggest using something like formatDate-js instead of trying to replicate it every time. Just use a library that supports all the major strftime actions.
new Date().format("%Y-%m-%d")
回答11:
You can try this: https://www.npmjs.com/package/timesolver
npm i timesolver
Use it in your code:
const timeSolver = require('timeSolver');
const date = new Date();
const dateString = timeSolver.getString(date, "YYYY-MM-DD");
You can get the date string by using this method:
getString
回答12:
None of these answers quite satisfied me. I wanted a cross-platform solution that gave 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.
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.
You'll need to polyfill Date.prototype.toISOString for it to work in Internet Explorer 8, but it should be supported everywhere else.
回答13:
Retrieve year, month, and day, and then put them together. Straight, simple, and accurate.
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()));
回答14:
To consider the timezone also, this one-liner should be good without any library:
new Date().toLocaleString("en-IN", {timeZone: "Asia/Kolkata"}).split(',')[0]
回答15:
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));
回答16:
Date.js is great for this.
require("datejs")
(new Date()).toString("yyyy-MM-dd")
回答17:
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>
回答18:
new Date(new Date(YOUR_DATE.toISOString()).getTime() -
(YOUR_DATE.getTimezoneOffset() * 60 * 1000)).toISOString().substr(0, 10)
回答19:
A few of the previous answer were OK, but they 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/
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.
// It 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');
回答20:
This worked for me to get the current date in the desired format (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);
回答21:
No library is needed
Just pure JavaScript.
The example below gets the last two months from today:
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))
回答22:
PHP compatible date format
Here is a small function which can take the same parameters as the PHP function date()
and return a date/time string in JavaScript.
Note that not all date() format options from PHP are supported. You can extend the parts
object to create the missing format-token
/**
* 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"
Gist
Here is a gist with an updated version of the formatDate()
function and additional examples: https://gist.github.com/stracker-phil/c7b68ea0b1d5bbb97af0a6a3dc66e0d9
回答23:
Reformatting a date string is fairly straightforward, 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));
回答24:
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));
回答25:
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);
}
回答26:
If the date needs to be the same across all time zones, for example represents some value from the database, then be sure to use UTC versions of the day, month, fullyear functions on the JavaScript date object as this will display in UTC time and avoid off-by-one errors in certain time zones.
Even better, use the Moment.js date library for this sort of formatting.
回答27:
I modified Samit Satpute's response as follows:
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);
回答28:
Format and finding maximum and minimum date from hashmap data:
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));
回答29:
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.
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);
回答30:
It is easily accomplished by my date-shortcode package:
const dateShortcode = require('date-shortcode')
dateShortcode.parse('{YYYY-MM-DD}', 'Sun May 11,2014')
//=> '2014-05-11'
来源:https://stackoverflow.com/questions/23593052/format-javascript-date-as-yyyy-mm-dd