var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;
document.write(today);
UBBER UPDATE After much procrastination, I've finally GitHubbed and updated this with the final solution I've been using for myself. It's even had some last-minute edits to make it sweeter! If you're looking for the old jsFiddle, please see this.
This update comes in 2 flavors, still relatively small, though not as small as my above, original answer. If you want extremely small, go with that. Also Note: This is still less bloated than moment.js. While moment.js is nice, imo, it has too many secular methods, which require learning moment as if it were a language. Mine here uses the same common format as PHP: date.
Flavor 1 new Date().format(String)
My Personal Fav. I know the taboo but works great on the Date Object. Just be aware of any other mods you may have to the Date Object.
// use as simple as
new Date().format('m-d-Y h:i:s'); // 07-06-2016 06:38:34
风味2: dateFormat(Date, String)
更传统的一体化方法。具有前一种方法的所有能力,但是通过带有 Date 参数的方法调用。
// use as simple as
dateFormat(new Date(), 'm-d-Y h:i:s'); // 07-06-2016 06:38:34
额外的风味(需要 jQuery) < a href = “ https://github.com/JDMcKinstry/jQuery-Date”rel = “ norefrer”> $.date(Date, String)
这不仅仅包含一个简单的 format选项。它扩展了基本 Date 对象并包括诸如 addDays之类的方法。有关详细信息,请参阅 Git。
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
<script>
function my_curr_date() {
var currentDate = new Date()
var day = currentDate.getDate();
var month = currentDate.getMonth() + 1;
var year = currentDate.getFullYear();
var my_date = month+"-"+day+"-"+year;
document.getElementById("dateField").value=my_date;
}
</script>
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear() + "-" + (month) + "-" + (day);
console.log(today);
/**
* Returns an array with date / time information
* Starts with year at index 0 up to index 6 for milliseconds
*
* @param {Date} date date object. If falsy, will take current time.
* @returns {[]}
*/
getDateArray = function(date) {
date = date || new Date();
return [
date.getFullYear(),
exports.pad(date.getMonth()+1, 2),
exports.pad(date.getDate(), 2),
exports.pad(date.getHours(), 2),
exports.pad(date.getMinutes(), 2),
exports.pad(date.getSeconds(), 2),
exports.pad(date.getMilliseconds(), 2)
];
};
下面是垫子的功能:
/**
* Pad a number with n digits
*
* @param {number} number number to pad
* @param {number} digits number of total digits
* @returns {string}
*/
exports.pad = function pad(number, digits) {
return new Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
};
var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];
var todaysDate = new Date(Date.now()).toLocaleString().slice(0,3).match(/[0-9]/i) ? new Date(Date.now()).toLocaleString().split(' ')[0].split(',')[0] : new Date(Date.now()).toLocaleString().split(' ')[1] + " " + new Date(Date.now()).toLocaleString().split(' ')[2] + " " + new Date(Date.now()).toLocaleString().split(' ')[3];
读起来真糟糕,不如这样:
var dateString = new Date(Date.now()).toLocaleString();
var todaysDate = dateString.slice(0,3).match(/[0-9]/i) ? dateString.split(' ')[0].split(',')[0] : dateString.split(' ')[1] + " " + dateString.split(' ')[2] + " " + dateString.split(' ')[3];
原始答案
我给你准备了一句俏皮话:
new Date(Date.now()).toLocaleString().split(', ')[0];
var dt = new Date();
/// ANY DATE YOU WANT -- dt = new Date(""July 21, 1983 01:15:00"")
dateObj = dt.getFormattedDate();
alert( dateObj.isToday() );
alert( dateObj.todayDay() );
alert( dateObj.monthNameDayYear() );
(function () {
fnDateProcessor = function () {
var that = this;
return {
yyyymmdd: function (separator) {
var fdate = this.formatDate(true, true) ,
separator = separator ? separator : "-";
return fdate.year + separator + fdate.month + separator + fdate.day;
},
monthNameDayYear: function () {
var fdate = this.formatDate(true, true);
return fdate.monthName + " " + fdate.day + ", " + fdate.year;
},
ddmmyyyy: function (separator) {
var fdate = this.formatDate(true, true) ,
separator = separator ? separator : "/";
return fdate.day + separator + fdate.month + separator + fdate.year;
},
meridianTime: function () {
var fdate = this.formatDate();
return fdate.hour + ":" + fdate.minute + " " + fdate.meridian;
},
monthDay: function (separator) {
var fdate = this.formatDate();
separator = checkSeparator(separator);
return fdate.monthName.substring(0, 3) + separator + fdate.day;
},
weekMonthDayYear: function () {
var fdate = this.formatDate();
//separator = checkSeparator(separator);
return fdate.weekDay + " " + fdate.monthName.substring(0, 3) +
fdate.day + " ," + fdate.year;
},
timeZoneInclusive: function () {
return new Date(that);
},
todayDay: function () { return new Date().getDate(); },
todayMonth: function () { return new Date().getMonth() + 1; },
dateDay: function () { return this.formatDate().day; },
dateMonth: function () { return this.formatDate().month; },
isToday: function () { return this.sameDate(new Date()); },
isYesterday: function () {
d = new Date(); d.setDate(d.getDate() - 1);
return this.sameDate(d);
},
formatDate: function () {
var zeroPaddedMnth = true, zeroPaddedDay = false,
zeroPaddedHr = false, zeroPaddedMin = true;
// Possible to take Options arg that overide / merge to defaults
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var weekDays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var day = getFormattedDay(that.getDate(), zeroPaddedDay);
var monthIndex = that.getMonth();
var month = getFormattedMonth(monthIndex + 1, zeroPaddedMnth);
var year = that.getFullYear();
var wkDay = that.getDay();
var hour = getFormattedHour(that.getHours(), zeroPaddedHr);
var minute = getFormattedMinute(that.getMinutes(), zeroPaddedMin);
var meridian = getMeridian(that.getHours());
return {
"day": day, "monthName": monthNames[monthIndex], "month": month,
"weekDay": weekDays[wkDay], "year": year, "hour": hour, "minute": minute,
"meridian": meridian
};
},
compareDate: function (d2) { /// validates if caller is less than argument
d2 = _isString(d2) ? new Date(d2) : d2;
return !this.sameDate(d2)
&& typeof d2 != "number"
? that < d2 : false;
},
sameDate: function (d) {
return that.getFullYear() === d.getFullYear()
&& that.getDate() === d.getDate()
&& that.getMonth() === d.getMonth();
},
dateAfter: function (separator) {
var fdate = this.formatDate();
var separator = separator ? separator : "-";
return fdate.year + separator + fdate.month + separator + (fdate.day + 1);
}
};
};
function _isString(obj) {
var toString = Object.prototype.toString;
return toString.call(obj) == '[object String]';
}
function checkSeparator(separator) {
// NOT GENERIC ... NEEDS REVISION
switch (separator) {
case " ": sep = separator; break;
case ",": sep = " ,"; break;
default:
sep = " "; break;
}
return sep;
}
function getFormattedHour(h, zeroPadded) {
h = h % 12;
h = h ? h : 12; // 12 instead of 00
return zeroPadded ? addZero(h) : h;
}
function getFormattedMinute(m, zeroPadded) {
return zeroPadded ? addZero(m) : m;
}
function getFormattedDay(dd, zeroPadded) {
return zeroPadded ? addZero(dd) : dd;
}
function getFormattedMonth(mm, zeroPadded) {
return zeroPadded ? addZero(mm) : mm;
}
function getMeridian(hr) {
return hr >= 12 ? 'PM' : 'AM';
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
Date.prototype.getFormattedDate = fnDateProcessor;
} ());
var date = new Date();
var timeZone = date.toString();
// Get timezone ('GMT+0200')
var timeZoneIndex = timeZone.indexOf('GMT');
// Cut optional string after timezone ('(heure de Paris)')
var optionalTimeZoneIndex = timeZone.indexOf('(');
if(optionalTimeZoneIndex != -1){
timeZone = timeZone.substring(timeZoneIndex, optionalTimeZoneIndex);
}
else{
timeZone = timeZone.substring(timeZoneIndex);
}
// Get date with JSON format ('2019-01-23T16:28:27.000Z')
var formattedDate = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toJSON();
// Cut ms
formattedDate = formattedDate.substring(0,formattedDate.indexOf('.'));
// Add timezone
formattedDate = formattedDate + ' ' + timeZone;
console.log(formattedDate);
// Declare Date as d
var d = new Date()
// Inline formatting of Date
const exampleOne = `${d.getDay()}-${d.getMonth() + 1}-${d.getFullYear()}`
// January is 0 so +1 is required
// With Breaklines and Operators
const exampleTwo = `+++++++++++
With Break Lines and Arithmetic Operators Example
Year on newline: ${d.getFullYear()}
Year minus(-) 30 years: ${d.getFullYear() - 30}
You get the idea...
+++++++++++`
console.log('=============')
console.log(exampleOne)
console.log('=============')
console.log(exampleTwo)
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var myDate = dd + '-' + mm + '-' + yyyy;
We use here standard JS functionalities: template literals, Date object which is cast to string, and slice. This is probably shortest solution which meet OP requirements (no time, only date)
// Get locale name
function getLang() {
if (navigator.languages != undefined)
return navigator.languages[0];
return navigator.language;
}
// Get the current datetime with format yyyy-MM-ddThhmmss
const time = new Date().toLocaleString(getLang(), {
hour12: false ,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: "numeric",
minute: "numeric",
second: "numeric"
}).replaceAll('/', '-').replaceAll(':', '').replaceAll(' ', 'T')
console.log("locale:", getLang())
console.log(time)