yy-mm-DD hh:mm:ss格式的时间 转为时间戳 js
时间: 2023-05-24 12:03:38 浏览: 255
A:
```javascript
let timeStr = 'yy-mm-DD hh:mm:ss'; // 时间字符串
let timestamp = new Date(timeStr).getTime();
console.log(timestamp); // 时间戳,单位为毫秒
```
注意,时间字符串中的 yy-mm-DD hh:mm:ss 需要替换为实际的时间字符串。另外,获取到的时间戳是以毫秒为单位的,需要根据需求进行转换。
相关问题
js将时间戳格式化为yy-mm-dd hh:mm:ss
你可以使用以下方法将 JavaScript 的时间戳格式化为 "yy-mm-dd hh:mm:ss" 的格式:
```javascript
function formatDate(timestamp) {
// 将时间戳转换为 JavaScript Date 对象
const date = new Date(timestamp);
// 获取年、月、日、小时、分钟和秒
const year = date.getFullYear().toString().slice(-2); // 提取年份的后两位
const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需要加1,并且补零
const day = String(date.getDate()).padStart(2, '0'); // 补零
const hours = String(date.getHours()).padStart(2, '0'); // 补零
const minutes = String(date.getMinutes()).padStart(2, '0'); // 补零
const seconds = String(date.getSeconds()).padStart(2, '0'); // 补零
// 构建格式化后的字符串
const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
return formattedDate;
}
// 示例使用
const timestamp = 1635798930000; // 假设时间戳为 1635798930000
console.log(formatDate(timestamp));
```
这将输出类似于 "21-11-01 09:28:50" 的格式化日期和时间字符串。你可以根据需要进行调整和修改。
yyyy-MM-dd HH:mm:ss 转为时间戳
时间戳是指从1970年1月1日00:00:00 UTC(协调世界时)开始计算的秒数。要将yyyy-MM-dd HH:mm:ss格式的时间转换为时间戳,您可以使用编程语言提供的日期时间函数或库。
以下是一个示例,假设您使用Python编程语言:
```python
import datetime
def convert_to_timestamp(date_string):
date_format = "%Y-%m-%d %H:%M:%S"
datetime_obj = datetime.datetime.strptime(date_string, date_format)
timestamp = datetime_obj.timestamp()
return int(timestamp)
date_string = "yyyy-MM-dd HH:mm:ss"
timestamp = convert_to_timestamp(date_string)
print(timestamp)
```
请将"yyyy-MM-dd HH:mm:ss"替换为您要转换的实际日期时间字符串。运行此代码将打印出相应的时间戳。