js数组 年月日时分秒格式进行排序
时间: 2023-06-25 16:06:02 浏览: 69
可以使用 JavaScript 中的 `sort()` 方法对包含年月日时分秒的数组进行排序。以下是一些示例代码:
```javascript
// 日期格式为年月日时分秒,例如:2021-05-16 14:30:00
const dates = ["2021-05-16 14:30:00", "2021-05-15 12:00:00", "2021-05-17 09:45:00"];
// 将日期字符串转换为日期对象并排序
const sortedDates = dates.map(dateStr => new Date(dateStr)).sort((a, b) => a - b);
// 将排序后的日期对象转换为字符串并输出
sortedDates.forEach(date => console.log(date.toLocaleString()));
```
这段代码会输出以下内容:
```
5/15/2021, 12:00:00 PM
5/16/2021, 2:30:00 PM
5/17/2021, 9:45:00 AM
```
你可以根据自己的需要对日期的格式和排序方式进行调整。
相关问题
数组 年月日时分秒转时间戳进行排序
可以先将数组中的年月日时分秒转换成时间戳,然后使用排序算法对时间戳进行排序,最后再将排序后的时间戳转换成日期时间格式。
以下是一个示例代码:
```python
import time
# 假设有一个数组存储了多个日期时间字符串
date_strs = ["2022-01-01 12:00:00", "2021-12-31 18:30:00", "2022-01-02 09:00:00"]
# 将日期时间字符串转换为时间戳并存储到新的数组中
timestamps = []
for date_str in date_strs:
timestamp = time.mktime(time.strptime(date_str, "%Y-%m-%d %H:%M:%S"))
timestamps.append(timestamp)
# 对时间戳进行排序
sorted_timestamps = sorted(timestamps)
# 将排序后的时间戳转换为日期时间字符串并打印出来
for timestamp in sorted_timestamps:
date_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
print(date_str)
```
输出结果为:
```
2021-12-31 18:30:00
2022-01-01 12:00:00
2022-01-02 09:00:00
```
js 获取 年月日时分秒 格式时间
你可以使用 JavaScript 内置的 Date 对象来获取当前时间,然后通过一些方法来获取年月日时分秒格式的时间。
以下是一个获取年月日时分秒格式时间的示例代码:
```javascript
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const date = now.getDate();
const hour = now.getHours();
const minute = now.getMinutes();
const second = now.getSeconds();
const time = `${year}-${month}-${date} ${hour}:${minute}:${second}`;
console.log(time); // 输出:2021-10-12 15:30:00
```
在这个代码中,我们首先创建了一个 Date 对象来获取当前时间。然后,使用 Date 对象的一些方法来获取年、月、日、时、分、秒等时间信息,并将它们拼接成一个年月日时分秒格式的时间字符串。最后,使用 console.log() 函数将时间字符串输出到控制台。
注意,这个示例代码中获取月份时需要加 1,因为 JavaScript 中的月份是从 0 开始计数的。