简体   繁体   中英

How to get date with specific time in javascript

I am trying to fetch 1st and last date and time of current month and I have to convert to ISOString. I tried below but when I am converting ISO its reducing 1 day and after removing it coming proper date.

I have to get 1st and last day of month with time..

This is what I want to have:

  • start datetime 2022-12-01T00:00:00.000Z
  • end datetime 2022-12-31T23:59:59.000Z

Here is my code:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
        
console.log(firstDay.toISOString())
console.log(lastDay.toISOString())

console.log(firstDay)
console.log(lastDay)

Result:

// ISO string:
2022-11-30T18:30:00.000Z
2022-12-30T18:30:00.000Z
// without ISO string:
VM4876:4 Thu Dec 01 2022 00:00:00 GMT+0530 (India Standard Time)
VM4876:5 Sat Dec 31 2022 00:00:00 GMT+0530 (India Standard Time)

You can use Date.UTC() to help you construct a date instance at the specified UTC datetime:

var firstDay = new Date(Date.UTC(y, m, 1));
var lastDay = new Date(Date.UTC(y, m + 1, 0, 23, 59, 59, 0));

Your date instances will now log the expected UTC time:

console.log(firstDay.toISOString())
console.log(lastDay.toISOString())

2022-12-01T00:00:00.000Z
2022-12-31T23:59:59.000Z
let currentDate = new Date();
let cDay = currentDate.getDate();
let cMonth = currentDate.getMonth() + 1;
let cYear = currentDate.getFullYear();
console.log("<b>" + cDay + "/" + cMonth + "/" + cYear + "</b>");

thats how you get date and time in js

i got it from here: https://www.w3docs.com/snippets/javascript/how-to-get-the-current-date-and-time-in-javascript.html

you might want to go over on how to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM