[php] Getting a timestamp for today at midnight?

How would I go about getting a timestamp in php for today at midnight. Say it's monday 5PM and I want the Timestamp for Monday(today) at midnight(12 am) which already has happened.

Thank you

This question is related to php time timestamp

The answer is


I think that you should use the new PHP DateTime object as it has no issues doing dates beyond the 32 bit restrictions that strtotime() has. Here's an example of how you would get today's date at midnight.

$today = new DateTime();
$today->setTime(0,0);

Or if you're using PHP 5.4 or later you can do it this way:

$today = (new DateTime())->setTime(0,0);

Then you can use the echo $today->format('Y-m-d'); to get the format you want your object output as.

PHP DateTime Object


_x000D_
_x000D_
function getTodaysTimeStamp() {_x000D_
  const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
  const startOfDay = currentTimeStamp - (currentTimeStamp % 86400);_x000D_
  return { startOfDay, endOfDay: startOfDay + 86400 - 1 };_x000D_
}_x000D_
_x000D_
// starts from sunday_x000D_
function getThisWeeksTimeStamp() {_x000D_
  const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
  const currentDay = new Date(currentTimeStamp * 1000);_x000D_
  const startOfWeek = currentTimeStamp - (currentDay.getDay() * 86400) - (currentTimeStamp % 86400);_x000D_
  return { startOfWeek, endOfWeek: startOfWeek + 7 * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
function getThisMonthsTimeStamp() {_x000D_
  const currentTimeStamp = Math.round(Date.now() / 1000);_x000D_
  const currentDay = new Date(currentTimeStamp * 1000);_x000D_
  const startOfMonth = currentTimeStamp - ((currentDay.getDate() - 1) * 86400) - (currentTimeStamp % 86400);_x000D_
  const currentMonth = currentDay.getMonth() + 1;_x000D_
  let daysInMonth = 0;_x000D_
  if (currentMonth === 2) daysInMonth = 28;_x000D_
  else if ([1, 3, 5, 7, 8, 10, 12].includes(currentMonth)) daysInMonth = 31;_x000D_
  else daysInMonth = 30;_x000D_
  return { startOfMonth, endOfMonth: startOfMonth + daysInMonth * 86400 - 1 };_x000D_
}_x000D_
_x000D_
_x000D_
console.log(getTodaysTimeStamp());_x000D_
console.log(getThisWeeksTimeStamp());_x000D_
console.log(getThisMonthsTimeStamp());
_x000D_
_x000D_
_x000D_


In more object way:

$today = new \DateTimeImmutable('today');

example:

 echo (new \DateTimeImmutable('today'))->format('Y-m-d H:i:s');
// will output: 2019-05-16 00:00:00

and:

echo (new \DateTimeImmutable())->format('Y-m-d H:i:s');
echo (new \DateTimeImmutable('now'))->format('Y-m-d H:i:s');
// will output: 2019-05-16 14:00:35

If you are using Carbon you can do the following. You could also format this date to set an Expire HTTP Header.

Carbon::parse('tomorrow midnight')->format(Carbon::RFC7231_FORMAT)

You are looking to calculate the time of the most recent celestial event where the sun has passed directly below your feet, adjusted for local conventions of marking high noon and also potentially adjusting so that people have enough daylight left after returning home from work, and for other political considerations.

Daunting right? Actually this is a common problem but the complete answer is location-dependent:

$zone = new \DateTimeZone('America/New_York'); // Or your own definition of “here”
$todayStart = new \DateTime('today midnight', $zone);
$timestamp = $todayStart->getTimestamp();

Potential definitions of “here” are listed at https://secure.php.net/manual/en/timezones.php


Updated Answer in 19 April, 2020

Simply we can do this:

$today = date('Y-m-d 00:00:00');


$today_at_midnight = strtotime(date("Ymd"));

should give you what you're after.

explanation

What I did was use PHP's date function to get today's date without any references to time, and then pass it to the 'string to time' function which converts a date and time to a epoch timestamp. If it doesn't get a time, it assumes the first second of that day.

References: Date Function: http://php.net/manual/en/function.date.php

String To Time: http://us2.php.net/manual/en/function.strtotime.php


Today at midnight. Easy.

$stamp = mktime(0, 0, 0);

$timestamp = strtotime('today midnight');

is the same as

$timestamp = strtotime('today');

and it's a little less work on your server.


$midnight = strtotime('midnight'); is valid
You can also try out strtotime('12am') or strtotime('[input any time you wish to here. e.g noon, 6pm, 3pm, 8pm, etc]'). I skipped adding today before midnight because the default is today.


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object

Examples related to timestamp

concat yesterdays date with a specific time How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Pandas: Convert Timestamp to datetime.date Spark DataFrame TimestampType - how to get Year, Month, Day values from field? What exactly does the T and Z mean in timestamp? What does this format means T00:00:00.000Z? Swift - iOS - Dates and times in different format Convert timestamp to string Timestamp with a millisecond precision: How to save them in MySQL