使用javascript写一个函数,格式化日期对象,最终输入形式为:yyyy/MM/dd HH:mm:ss。比如:
时间: 2024-03-21 08:40:27 浏览: 21
好的,以下是一个简单的函数可以实现你的要求:
```javascript
function formatDate(date) {
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2);
const day = ('0' + date.getDate()).slice(-2);
const hours = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
const seconds = ('0' + date.getSeconds()).slice(-2);
return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
}
```
你可以传入一个日期对象,比如`new Date()`,调用该函数即可得到格式化后的日期字符串。
相关问题
js写一个获取两小时前的时间并返回日期格式化为yyyy-MM-dd hh:mm:ss的函数
好的,以下是获取两小时前的日期并返回格式化的函数。请注意,这个函数需要在浏览器环境下运行,因为它使用了Date对象和地时间,而不是服务器时间。
```javascriptfunction getDateTwoHoursAgo() {
const now = new Date();
const twoHoursAgo = new Date(now.getTime() - 2 * 60 * 60 * 1000);
const year = twoHoursAgo.getFullYear();
const month = String(twoHoursAgo.getMonth() + 1).padStart(2, '0');
const day = String(twoHoursAgo.getDate()).padStart(2, '0');
const hour = String(twoHoursAgo.getHours()).padStart(2, '0');
const minute = String(twoHoursAgo.getMinutes()).padStart(2, '0');
const second = String(twoHoursAgo.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}
```
使用示例:
```javascript
const twoHoursAgo = getDateTwoHoursAgo();
console.log(twoHoursAgo); // 例如:2021-12-18 12:23:45
```
js时间格式化yyyy-mm-dd hh:MM:ss
你可以使用 JavaScript 的 Date 对象来格式化日期时间。以下是一个示例函数,将 Date 对象转换为格式为 "yyyy-mm-dd hh:MM:ss" 的字符串:
```javascript
function formatDate(date) {
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var hour = ('0' + date.getHours()).slice(-2);
var minute = ('0' + date.getMinutes()).slice(-2);
var second = ('0' + date.getSeconds()).slice(-2);
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
}
// 示例使用
var date = new Date();
console.log(formatDate(date)); // 输出格式为 "yyyy-mm-dd hh:MM:ss" 的当前日期时间字符串
```
请注意,上述代码中的 `slice(-2)` 用于确保月份、日期、小时、分钟和秒数都是两位数字。如果某个值小于 10,则将其前面添加一个零。