用js编写函数,把当前时间格式化成 YYYY-MM-DD HH-mm-ss
时间: 2024-01-05 09:04:54 浏览: 30
好的,以下是用 JavaScript 编写的函数,可以将当前时间格式化为 YYYY-MM-DD HH:mm:ss 的形式:
```javascript
function formatDate() {
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
const seconds = date.getSeconds().toString().padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
```
请问,还有什么问题我可以帮到您?
相关问题
编写函数,把当前时间格式化成 YYYY-MM-DD HH-mm-ss
好的,以下是一个可用的Python函数:
```
import datetime
def format_time():
now = datetime.datetime.now()
date_format = now.strftime("%Y-%m-%d %H:%M:%S")
return date_format
```
你可以直接调用这个函数来将当前时间格式化为 YYYY-MM-DD HH-mm-ss 的形式。
js 获取当前时间,格式为YYYY-MM-DD hh-mm-ss
你可以使用 JavaScript 的 Date 对象来获取当前时间,并使用一些方法来格式化时间。以下是一个获取当前时间并格式化为 "YYYY-MM-DD hh:mm:ss" 的示例代码:
```javascript
// 创建 Date 对象
const currentDateTime = new Date();
// 获取年、月、日、时、分、秒
const year = currentDateTime.getFullYear();
const month = String(currentDateTime.getMonth() + 1).padStart(2, '0');
const day = String(currentDateTime.getDate()).padStart(2, '0');
const hours = String(currentDateTime.getHours()).padStart(2, '0');
const minutes = String(currentDateTime.getMinutes()).padStart(2, '0');
const seconds = String(currentDateTime.getSeconds()).padStart(2, '0');
// 格式化时间
const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(formattedDateTime); // 输出格式化后的时间
```
在上述代码中,我们首先创建一个 Date 对象来获取当前时间。然后使用 Date 对象提供的一些方法,如 `getFullYear()`、`getMonth()`、`getDate()`、`getHours()`、`getMinutes()` 和 `getSeconds()` 来获取年、月、日、时、分和秒。接着,我们使用 `padStart()` 方法来确保每个时间部分都是两位数,如果不足两位,则在左侧填充零。最后,我们将这些时间部分按照 "YYYY-MM-DD hh:mm:ss" 的格式进行拼接,并将结果打印到控制台。
你可以将上述代码放入你的 JavaScript 文件中,然后调用相应的函数来获取格式化后的当前时间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)