export const getDateFormList = () => { const datenow = new Date(); const YYYY = datenow.getFullYear().toString(); //年 const M = (datenow.getMonth() + 1).toString(); //月 const MM = M.length === 1 ? `0${M}` : M; //月 const D = datenow.getDate().toString(); //日 const DD = D.length === 1 ? `0${D}` : D; //日 return [ `${YYYY}-${MM}-${DD} 00:00:00`, `${YYYY}-${MM}-${DD} 23:59:59`, ] }
时间: 2023-08-12 14:08:53 浏览: 52
好的,下面是改造后的代码,可以实现获取当前日期及未来两天的日期:
```
export const getDateFormList = () => {
const dateNow = new Date();
const dates = [];
// 获取当前日期及未来两天的日期
for (let i = 0; i < 3; i++) {
const date = new Date(dateNow.getTime() + i * 24 * 60 * 60 * 1000);
const YYYY = date.getFullYear().toString(); // 年
const M = (date.getMonth() + 1).toString(); // 月
const MM = M.length === 1 ? `0${M}` : M; // 月
const D = date.getDate().toString(); // 日
const DD = D.length === 1 ? `0${D}` : D; // 日
dates.push(`${YYYY}-${MM}-${DD}`);
}
return dates;
}
```
以上代码会返回一个包含当前日期及未来两天日期的数组,格式为 `YYYY-MM-DD`。您可以根据您的实际需求来调整日期格式。
相关问题
获取当前时间,将new Date()转换成yyyy-MM-dd格式
可以使用以下的JavaScript代码获取当前时间,并将new Date()对象转换成yyyy-MM-dd格式的字符串:
```javascript
const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
const hours = now.getHours().toString().padStart(2, '0');
const minutes = now.getMinutes().toString().padStart(2, '0');
const seconds = now.getSeconds().toString().padStart(2, '0');
const formattedDate = `${year}-${month}-${day}`;
const formattedTime = `${hours}:${minutes}:${seconds}`;
console.log(`当前时间为:${formattedDate} ${formattedTime}`); // 输出格式化后的日期和时间字符串,例如:当前时间为:2022-01-01 12:34:56
```
这段代码中,我们使用了之前提到的方法将日期对象转换成yyyy-MM-dd格式的字符串。同时,我们还获取了当前时间的小时、分钟和秒,并将它们拼接成一个格式为HH:mm:ss的字符串。最后,我们使用模板字符串将日期和时间拼接起来,并打印输出。
ts Date 原型增强 格式化函数 形参为格式化字符串模板
你可以通过为 `Date.prototype` 添加一个新的方法来实现格式化日期的功能。这样,你就可以在任何 `Date` 对象上调用这个方法,而无需每次都传递格式化字符串模板作为参数。
以下是一个示例代码:
```typescript
interface Date {
format(template: string): string;
}
Date.prototype.format = function (template: string): string {
const year = this.getFullYear();
const month = `0${this.getMonth() + 1}`.slice(-2);
const day = `0${this.getDate()}`.slice(-2);
const hours = `0${this.getHours()}`.slice(-2);
const minutes = `0${this.getMinutes()}`.slice(-2);
const seconds = `0${this.getSeconds()}`.slice(-2);
return template.replace('yyyy', year.toString())
.replace('MM', month)
.replace('dd', day)
.replace('HH', hours)
.replace('mm', minutes)
.replace('ss', seconds);
};
const now = new Date();
console.log(now.format('yyyy-MM-dd HH:mm:ss')); // 2022-08-05 14:30:00
```
在这个示例中,我们向 `Date.prototype` 添加了一个名为 `format` 的新方法。该方法接受一个字符串模板作为参数,用来指定输出格式。在方法内部,我们通过调用 `this` 来获取当前日期的各个部分,并使用字符串的 `replace` 方法将模板中的占位符替换为相应的日期值。最后,我们返回格式化后的日期字符串。
使用这个方法,你可以在任何 `Date` 对象上调用 `format` 方法,并传递一个格式化字符串模板作为参数,以获取格式化后的日期字符串。例如:
```typescript
const date = new Date(2022, 7, 5, 14, 30, 0);
console.log(date.format('yyyy-MM-dd HH:mm:ss')); // 2022-08-05 14:30:00
```