How to get timestamp of current month, first day of month, zero hour
Asked Answered
L

3

28

I am trying to get the timestamp of the first day of the month at 00:00:00.

For example, the timestamp of Jan 01 2012 00:00:00

I'm doing this:

$test_month = time(); // Seconds
$test_month = date('M', $test_month); // This month
$test_month = strtotime($test_month); // Timestamp of this month
echo $test_month;

This is returning zero hour of the current day of the month, not the start of the month.

Any suggestions?

Later answered 28/6, 2012 at 0:47 Comment(0)
T
24

Try this:

echo date( 'F jS Y h:i:s A', strtotime( 'first day of ' . date( 'F Y')));

This will output:

June 1st 2012 12:00:00 AM
Thematic answered 28/6, 2012 at 0:55 Comment(5)
Wow, I didnt even know 'first day of' existed. Great! Thanks.Later
@JohnRobinson - You're welcome! It's actually documented on the list of supported relative times. If my post answered your question, please consider accepting it.Thematic
You don't need to use date('F Y'), you can just use strtotime('first day of this month'). You can even add a timestamp of another time as the second argument to get the first day of it's month.Tombolo
strtotime("first day of this month midnight"). Adding midnight will result in 12:00AM.Arvie
Doesn't look like a rememberable solution to me, because of the usings of the F, jS placeholders. Would prefer the database format like in the other answers. Whereas simply using strtotime('first of this month') (without date parameter) seems to be a good, possibly rememberable solution, too.Gaulin
V
18

Try this

$time = strtotime(date('Y-m-01 00:00:00')); // == 1338534000

Which translates to:

$date = date('Y-m-d H:i:s', $time); // == 2012-06-01 00:00:00

Read the PHP manual on the date() and time() functions.

Vespasian answered 28/6, 2012 at 0:54 Comment(1)
Looks like a more intuitive solution to me than the one of @Thematic https://mcmap.net/q/491152/-how-to-get-timestamp-of-current-month-first-day-of-month-zero-hour. Thanks!Gaulin
C
5
echo date("Y-m-d 00:00:00", strtotime("first day of this month"));

This outputs:

2017-05-01 00:00:00
Capacitor answered 27/5, 2017 at 5:39 Comment(1)
This answer looks also cleaner than the solution in https://mcmap.net/q/491152/-how-to-get-timestamp-of-current-month-first-day-of-month-zero-hour, because the format is more frequently used, I think.Gaulin

© 2022 - 2024 — McMap. All rights reserved.