我想知道如何在jQuery中使用Date()函数以yyyy/mm/dd格式获取当前日期。
当前回答
因为问题被标记为jQuery:
如果你也在使用jQuery UI,你可以使用$.datepicker.formatDate():
$.datepicker.formatDate('yy/mm/dd', new Date());
请看这个演示。
其他回答
Date()不是jQuery的一部分,它是JavaScript的特性之一。
请参阅有关Date对象的文档。
你可以这样做:
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
请看jsfiddle的证明。
代码可能看起来很复杂,因为它必须处理用小于10的数字表示的月和日(这意味着字符串将有一个字符而不是两个)。请参阅jsfiddle进行比较。
Moment.js让它变得非常简单:
moment().format("YYYY/MM/DD")
下面是获取当前日、年或月的方法
new Date().getDate() // Get the day as a number (1-31)
new Date().getDay() // Get the weekday as a number (0-6)
new Date().getFullYear() // Get the four digit year (yyyy)
new Date().getHours() // Get the hour (0-23)
new Date().getMilliseconds() // Get the milliseconds (0-999)
new Date().getMinutes() // Get the minutes (0-59)
new Date().getMonth() // Get the month (0-11)
new Date().getSeconds() // Get the seconds (0-59)
new Date().getTime() // Get the time (milliseconds since January 1, 1970)
如果你有jQuery UI(需要datepicker),这将做的伎俩:
$.datepicker.formatDate('yy/mm/dd', new Date());
你可以这样做:
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
或者类似的东西
var dateObj = new Date();
var month = dateObj.getUTCMonth();
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var newdate = month + "/" + day + "/" + year;
alert(newdate);
推荐文章
- Javascript和regex:分割字符串并保留分隔符
- 如何检查DST(日光节约时间)是否有效,如果是,偏移量?
- 如何打破_。在underscore.js中的每个函数
- 如何在jQuery中获得当前日期?
- 如何创建一个日期对象从字符串在javascript
- 输入触发器按钮单击
- 获取对象的属性名
- 如何检查用户是否可以回到浏览器历史
- 使用jQuery的“.val()”在表单中设置隐藏字段的值不工作
- 相当于字符串。jQuery格式
- jQuery模板引擎
- 如何在vue-cli项目中更改端口号
- Angular 2模板中的标签是什么意思?
- JavaScript .includes()方法的多个条件
- 窗口。亲近与自我。close不关闭Chrome中的窗口