如何在JavaScript中获取当前日期?
当前回答
要获取日期,则将其内置到JavaScript中:
new Date();
如果您正在寻找日期格式,并且无论如何都在为您的网站使用Kendo jQuery UI库,那么我建议使用内置的Kendo函数:
kendo.toString(new Date(), "yyMMdd"); // Or any other typical date format
有关支持格式的完整列表,请参阅此处。
其他回答
我认为这是一个老问题,但最简单的方法是:
var date = new Date();
var TimeStamp = date.toLocaleString();
function CurrentTime(){
alert(TimeStamp);
}
这将获取当前时间,根据位置将其传递给字符串,然后您可以调用函数CurrentTime来显示时间。对我来说,这将是获取时间戳的最有效方法。
如果您希望格式化为字符串。
statusUpdate = "time " + new Date(Date.now()).toLocaleTimeString();
输出:“时间11:30:53 AM”
我的解决方案使用字符串文字。了解更多信息。。。
//声明日期为dvar d=新日期()//日期的内联格式const exampleOne=`${d.getDay()}-${d.getMonth()+1}-${d.getFullYear()}`//一月为0,因此需要+1//使用特征线和运算符常量示例二=`+++++++++++带换行符和算术运算符示例新行上的年份:${d.getFullYear()}年份减(-)30年:${d.getFullYear()-30}你明白了。。。+++++++++++`console.log('============')console.log(示例一)console.log('============')console.log(示例二)
您可以使用扩展Date对象的Date.js库,因此可以使用.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函数:
/**
* 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;
};
最后,我可以手动创建日期字符串,也可以使用一个简单的函数来实现:
/**
* Returns nicely formatted date-time
* @example 2015-02-10 16:01:12
*
* @param {object} date
* @returns {string}
*/
exports.niceDate = function(date) {
var d = exports.getDateArray(date);
return d[0] + '-' + d[1] + '-' + d[2] + ' ' + d[3] + ':' + d[4] + ':' + d[5];
};
/**
* Returns a formatted date-time, optimized for machines
* @example 2015-02-10_16-00-08
*
* @param {object} date
* @returns {string}
*/
exports.roboDate = function(date) {
var d = exports.getDateArray(date);
return d[0] + '-' + d[1] + '-' + d[2] + '_' + d[3] + '-' + d[4] + '-' + d[5];
};
推荐文章
- ReactJS和公共文件夹中的图像
- 在React Native中使用Fetch授权头
- 为什么我的球(物体)没有缩小/消失?
- 如何使用jQuery检测页面的滚动位置
- if(key in object)或者if(object. hasownproperty (key)
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象