let time=new Date().toLocaleDateString() 例如 2023/6/2 转换为2023-06-02
时间: 2024-03-02 13:52:51 浏览: 34
可以使用字符串的 replace() 方法和正则表达式来实现日期格式的转换。具体地,可以将斜杠替换为横杆,代码如下:
```
let time = new Date().toLocaleDateString().replace(/\//g, '-');
```
其中,正则表达式 /\//g 匹配所有的斜杠,并使用 replace() 方法将其替换为横杆。最终的结果就是一个形如 "2023-6-2" 的字符串。如果需要补全月份和日期的零位,可以对日期做一些处理,代码如下:
```
let date = new Date();
let year = date.getFullYear();
let month = (date.getMonth() + 1).toString().padStart(2, '0');
let day = date.getDate().toString().padStart(2, '0');
let time = `${year}-${month}-${day}`;
```
其中,padStart() 方法用于在字符串前面补全指定的字符,确保字符串的长度达到指定的长度。这里将月份和日期都转换为字符串,并使用 padStart() 方法补全零位。最终的结果就是一个形如 "2023-06-02" 的字符串。
相关问题
date输出值为2023/6/9,怎么转化为2023-6-9
你可以使用 JavaScript 的字符串方法 `replace()` 和正则表达式来将日期格式中的斜杠 `/` 替换为短横线 `-`。可以使用以下代码实现:
```javascript
const date = new Date('2023/6/9');
const formattedDate = date.toLocaleDateString().replace(/\//g, '-');
console.log(formattedDate); // "2023-6-9"
```
在上面的代码中,首先创建了一个日期对象 `date`,其值为 `2023/6/9`。然后使用 `toLocaleDateString()` 方法将其转换为本地日期字符串。最后,使用字符串方法 `replace()` 和正则表达式 `/\/g` 来全局替换斜杠 `/` 为短横线 `-`,得到了格式化后的日期字符串 `formattedDate`,其值为 `2023-6-9`。
function replaceDate(input) { var date = input.value; var text = new Date(date).toLocaleDateString(); var span = document.createElement('span'); span.innerHTML = text; input.parentNode.insertBefore(span, input); input.style.display = 'none'; input.setAttribute('data-value', date); } function restoreDate(button) { // 获取所在行 var row = button.parentNode.parentNode; // 获取该行的日期选择器 var input = row.querySelector('input[type="date"]'); // 恢复日期选择器 input.style.display = 'inline-block'; input.value = input.dataset.originalValue; // 移除提示信息 var span = input.parentNode.querySelector('span'); input.parentNode.removeChild(span); }正确吗
这段代码看起来是有问题的。首先,函数`replaceDate`中的`input`参数应该是一个DOM元素,而不是一个包含值的对象。其次,在`restoreDate`函数中,`input.dataset.originalValue`没有被定义,应该使用`input.getAttribute('data-value')`来获取之前保存的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![.zip](https://img-home.csdnimg.cn/images/20210720083646.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)