[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


$timestamp = strtotime('today midnight');

You might want to take a look what PHP has to offer: http://php.net/datetime


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


Today at midnight. Easy.

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

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


$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


Updated Answer in 19 April, 2020

Simply we can do this:

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


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

$timestamp = strtotime('today midnight');

is the same as

$timestamp = strtotime('today');

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


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)

$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.


_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_


Questions with php tag:

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? Target class controller does not exist - Laravel 8 Message: Trying to access array offset on value of type null Array and string offset access syntax with curly braces is deprecated Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error How to fix "set SameSite cookie to none" warning? The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"? dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac What does double question mark (??) operator mean in PHP Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client php mysqli_connect: authentication method unknown to the client [caching_sha2_password] Converting a POSTMAN request to Curl Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required Issue in installing php7.2-mcrypt Xampp localhost/dashboard How can I run specific migration in laravel How to change PHP version used by composer Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory Artisan migrate could not find driver phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO) Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) laravel 5.5 The page has expired due to inactivity. Please refresh and try again "The page has expired due to inactivity" - Laravel 5.5 How to increment a letter N times per iteration and store in an array? Can't install laravel installer via composer Only on Firefox "Loading failed for the <script> with source" Is there way to use two PHP versions in XAMPP? How to prevent page from reloading after form submit - JQuery laravel Eloquent ORM delete() method No Application Encryption Key Has Been Specified General error: 1364 Field 'user_id' doesn't have a default value How to logout and redirect to login page using Laravel 5.4? How to uninstall an older PHP version from centOS7 How to Install Font Awesome in Laravel Mix PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers Laravel - htmlspecialchars() expects parameter 1 to be string, object given How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

Questions with time tag:

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 Swift convert unix time to date and time Python get current time in right timezone PHP: How to check if a date is today, yesterday or tomorrow How to parse unix timestamp to time.Time Python loop to run for certain amount of seconds Go / golang time.Now().UnixNano() convert to milliseconds? What is the `zero` value for time.Time in Go? How to extract epoch from LocalDate and LocalDateTime? how to sync windows time from a ntp time server in command Exception in thread "main" java.lang.Error: Unresolved compilation problems PHP Converting Integer to Date, reverse of strtotime How to get current time with jQuery Get current time in hours and minutes How to format current time using a yyyyMMddHHmmss format? How to print the current time in a Batch-File? Should MySQL have its timezone set to UTC? Checking Date format from a string in C# Get the time difference between two datetimes Convert Java string to Time, NOT Date Creating a timer in python How do I measure request and response times at once using cURL? How to delete last item in list? How do I use .toLocaleTimeString() without displaying seconds? Converting Milliseconds to Minutes and Seconds? How to multiply duration by integer? Oracle date format picture ends before converting entire input string How to print current date on python3? Convert java.util.date default format to Timestamp in Java What is the easiest way to get current GMT time in Unix timestamp format? Command to get time in milliseconds Creating java date object from year,month,day Current date and time as string how to re-format datetime string in php? Update TextView Every Second Current time formatting with Javascript How to measure time taken between lines of code in python? Is Android using NTP to sync time? Getting time difference between two times in PHP Does Python's time.time() return the local or UTC timestamp? PHP: How to get current time in hour:minute:second?

Questions with timestamp tag:

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 Ping with timestamp on Windows CLI How to change default format at created_at and updated_at value laravel How to convert java.sql.timestamp to LocalDate (java8) java.time? How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss" How to parse/format dates with LocalDateTime? (Java 8) Get records of current month How to get correct timestamp in C# How to format current time using a yyyyMMddHHmmss format? Convert datetime to Unix timestamp and convert it back in python Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset) How to get current timestamp in milliseconds since 1970 just the way Java gets How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) Function to convert timestamp to human date in javascript java.util.Date format SSSSSS: if not microseconds what are the last 3 digits? When is a timestamp (auto) updated? Java: Convert String to TimeStamp best practice to generate random token for forgot password Getting date format m-d-Y H:i:s.u from milliseconds How to get the unix timestamp in C# SQL Server 2008 Row Insert and Update timestamps Create timestamp variable in bash script Convert java.util.date default format to Timestamp in Java Using current time in UTC as default value in PostgreSQL How to convert UTC timestamp to device local time in android How to select rows that have current day's timestamp? How to have an automatic timestamp in SQLite? How do I convert dmesg timestamp to custom date format? Getting a timestamp for today at midnight? DB2 Timestamp select statement How to convert TimeStamp to Date in Java? How do I get the unix timestamp in C as an int? MySQL convert date string to Unix timestamp '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error How to convert from java.sql.Timestamp to java.util.Date? SQL Server: Cannot insert an explicit value into a timestamp column Getting time and date from timestamp with php How to convert integer timestamp to Python datetime What does the 'Z' mean in Unix timestamp '120314170138Z'? CURRENT_TIMESTAMP in milliseconds How do I automatically update a timestamp in PostgreSQL