js中获取今天日期,不加时间
时间: 2023-07-09 11:18:26 浏览: 52
你可以使用JavaScript的Date对象来获取今天的日期,具体代码如下:
```javascript
const today = new Date();
const year = today.getFullYear(); // 获取年份
const month = today.getMonth() + 1; // 获取月份,需要加1
const day = today.getDate(); // 获取日
const todayStr = year + '-' + month + '-' + day; // 拼接成日期字符串
console.log(todayStr); // 输出格式为:YYYY-MM-DD,例如:2022-02-22
```
这样就可以获取到今天的日期,不包含时间。
相关问题
javascr中只获取时间,不获取日期的方法
在 JavaScript 中,可以使用 Date 对象的方法来获取时间部分,然后进行格式化或其他操作。
以下是几种获取时间部分的方法:
1. 使用 Date 对象的 toTimeString() 方法
可以使用 Date 对象的 toTimeString() 方法来获取时间部分的字符串。示例代码如下:
```javascript
var now = new Date();
var timeString = now.toTimeString().split(' ')[0];
```
其中,now 是一个 Date 对象,timeString 是时间部分的字符串。
2. 使用 Date 对象的 getHours()、getMinutes()、getSeconds() 方法
也可以使用 Date 对象的 getHours()、getMinutes()、getSeconds() 方法来分别获取小时、分钟、秒数,然后拼接成时间字符串。示例代码如下:
```javascript
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var timeString = hours + ':' + minutes + ':' + seconds;
```
需要注意的是,以上两种方法都是获取本地时间,如果需要获取 UTC 时间,可以使用对应的 UTC 方法(例如:toUTCString()、getUTCHours()、getUTCMinutes()、getUTCSeconds())。另外,需要根据具体情况进行时间格式化和时区转换等操作。
js 获取当前日期时间
可以使用 JavaScript 的内置对象 Date() 来获取当前日期时间。
以下是获取当前日期时间的示例代码:
```
// 创建一个 Date 对象
let currentDate = new Date();
// 获取当前年份
let year = currentDate.getFullYear();
// 获取当前月份(注意:返回值从 0 开始,即 0 表示一月,1 表示二月,以此类推)
let month = currentDate.getMonth() + 1;
// 获取当前日期
let date = currentDate.getDate();
// 获取当前小时数(0-23)
let hours = currentDate.getHours();
// 获取当前分钟数
let minutes = currentDate.getMinutes();
// 获取当前秒数
let seconds = currentDate.getSeconds();
// 输出当前日期时间
console.log(year + "-" + month + "-" + date + " " + hours + ":" + minutes + ":" + seconds);
```
输出结果类似于:2022-02-22 10:30:15
相关推荐
![](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)