jQuery本身不直接提供日期格式处理功能,但可以通过jQuery结合JavaScript的Date对象或第三方日期处理库(如moment.js、date-fns等)来实现日期格式处理。
// 获取当前日期
var now = new Date();
// 格式化日期
function formatDate(date) {
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
return year + '-' + month + '-' + day;
}
// 使用示例
var formattedDate = formatDate(now);
console.log(formattedDate); // 输出如:2023-05-15
$.datepicker.formatDate('yy-mm-dd', new Date());
// 需要先引入moment.js
var now = moment();
console.log(now.format('YYYY-MM-DD')); // 2023-05-15
console.log(now.format('YYYY/MM/DD')); // 2023/05/15
console.log(now.format('YYYY年MM月DD日')); // 2023年05月15日
console.log(now.format('MMMM Do, YYYY')); // May 15th, 2023
2023-05-15T14:30:00.000Z
05/15/2023
或 2023-05-15
May 15, 2023
或 2023年5月15日
May 15, 2023 2:30:00 PM
原因:通常是因为尝试格式化非日期对象或无效日期字符串
解决方案:
// 确保传入的是有效日期
function safeFormatDate(date) {
var d = new Date(date);
if(isNaN(d.getTime())) {
return 'Invalid Date';
}
return formatDate(d); // 使用前面定义的formatDate函数
}
原因:JavaScript Date对象会使用本地时区
解决方案:
// 使用UTC方法
function formatUTCDate(date) {
var year = date.getUTCFullYear();
var month = ('0' + (date.getUTCMonth() + 1)).slice(-2);
var day = ('0' + date.getUTCDate()).slice(-2);
return year + '-' + month + '-' + day;
}
解决方案:
// 加一天
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
// 使用moment.js更简单
var tomorrow = moment().add(1, 'days');