-2

Good morning, I currently have this script:

now = new Date (). getTime ();
now = now + 86400000;

this takes the current date and time and adds 24 hours to it.

Instead, I would need to set midnight of the current day. I tried with:

var d = new Date ();
date = d.setHours (0,0,0,0);
now = date / 1000;

but it does not work! I need this to set the expiration of a cookie:

$ .cookies.set ('mycookie2250', 'true', {expiresAt: new Date (now)});

in the first case it works but in the second it doesn't. Where am I wrong?

Igor
  • 1
  • 1
  • 1
    it would help if you had a look at the Date library, particularly `setHours()` and so on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setHours – Nico Mar 15 '21 at 14:20
  • 1
    Why are you dividing the date by 1000? You already have the date in milliseconds you can directly create a date object with it. – Hassan Imam Mar 15 '21 at 14:21
  • Define "does not work". `d.setHours(0,0,0,0)` gets local midnight at the start of the day. If you want the end of the day (i.e. midnight at the start of tomorrow), then `d.setHours(24,0,0,0)` does the trick. – RobG Mar 15 '21 at 21:39
  • I did it divided by 1000 because doing some research I had seen this example. Sorry but I'm not an expert. Now I have tried: var date = new Date (); date.setHours (0,0,0,0); and that's correct because it takes me midnight today. But I believe there is still a problem with writing the cookie. I tried both like this (i.e. as it was originally): $.cookies.set ('mycookie2250', 'true', {expiresAt: new Date (date)}); that like this: $.cookies.set ('mycookie2250', 'true', {expiresAt: date}); – Igor Mar 16 '21 at 08:13
  • I think I understand my problem ... As indicated by @RobG I was using d.setHours (0,0,0,0) but this is the beginning of the day so a time has already passed. This is why the cookie is not written. I have to use precisely: d.setHours (24,0,0,0) – Igor Mar 16 '21 at 08:32

1 Answers1

0
var date = new Date();
date.setHours(0,0,0,0);

// date is midnight.
Nico
  • 790
  • 1
  • 8
  • 20
  • Thanks but I have two doubts: 1) the +1 I see in the line: date.setDate (date.getDate () + 1); takes me the date tomorrow. I need today's one so I guess just remove it. 2) do I no longer have to divide by 1000? – Igor Mar 15 '21 at 15:16
  • You are correct, I removed that line in my answer. Why do you need to divide by 1000? `date` is the object. If you want to get unixtime `ms` just do `.getTime()`, otherwise do `.getTime() / 1000`. However, since it's for a cookie, you can just convert the date to UTC by doing `date.toISOString()` – Nico Mar 15 '21 at 15:44