javascript - How to convert string to date object in javascript?
问题描述
I have a date string like '2019-06-12 12:02:12 232
',how to convert to date using Javascript?
Date date = Date.parse('2019-06-12 12:02:12 232').format('yyyy-MM-dd dd:HH:ss SSS');
I want to compare two date to calculate the minisecond in Javascript.Any suggestion?How could I tweak my date string?The date string was generate is server side using Java:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss SSS");
String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
This question does not contain minisecond,if no minisecond,Date.parse could solved the problem.My question is precise contain more detail operation of Javascript Date.
解决方案
You can do it like that:
let date_string = "2019-06-12 12:02:12 232"
let [y,M,d,h,m,s] = date_string.split(/[- :]/);
let yourDate = new Date(y,parseInt(M)-1,d,h,parseInt(m),s);
console.log(`yourDate ${yourDate}`);
In addition, avoid using Date.parse()
method.
UPDATE:
By using the above approach, you will avoid some strange bugs as described in the above link. However, it is possible to use a great library Moment.js
:
moment("12-25-1995", "MM-DD-YYYY");
In addition, you could check if a date is valid:
moment("whether this date is valid").isValid(); // OUTPUT: false
推荐阅读
- laravel - 从 laravel 中的 json 中删除枢轴键
- javascript - 如何选择生成多少个随机字符串?
- vue.js - 从 .js 文件 vuejs 访问组件
- ios - 将数据保存在来自 ios swift 中 2 个不同 uitableviews 的数组中
- xml - 努力理解 Google 表格 IMPORTXML 和 Xpath
- android - 是否可以使用 firebase ML 套件检测性别
- r - 找到两个文本之间的最大距离并绑定它们
- function-pointers - Emonlib+ADS1115+ESP32+Arduino 函数指针
- javascript - 赛普拉斯 - 断言仅存在一个带有文本的元素
- c# - 从纯文本中解析换行符