Home > Software design >  How to get date with specific time in javascript
How to get date with specific time in javascript

Time:12-14

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 . Please help I have to get 1st and last day of month with time ..

my expectation below

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

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m   1, 0);

console.log(firstDay.toISOString())
console.log(lastDay.toISOString())
2022-11-30T18:30:00.000Z
2022-12-30T18:30:00.000Z

 withought IOS
console.log(firstDay)
console.log(lastDay)
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)

Thanks

CodePudding user response:

You can use Date.UTC() to help you construct a date instance in UTC:

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

Your date instances will now be in UTC time:

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

2022-12-01T00:00:00.000Z
2022-12-31T00:00:00.000Z

CodePudding user response:

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.

  • Related