Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first day of previous month at 00:00:00 using DateTime?

Tags:

php

datetime

How do I get first day of previous month with start time? I am currently using this:

$date = new DateTime('first day of last month');

It gives me the first day of last month but with respect to my current time. What I'm actually trying to do is get the start with respect to timezone too. For example:

$date = new DateTime('first day of previous month', 
new DateTimeZone('UTC'));

Result would be July 1st, 2013 00:00:00. Or if I use:

$date = new DateTime('first day of previous month', 
new DateTimeZone('Europe/Amsterdam'));

Expected result: June 30, 2013 21:00:00 (because of its offset).

How can I do this using PHP?

like image 451
Jane Deuschandell Avatar asked Dec 26 '13 08:12

Jane Deuschandell


1 Answers

Just add time (time formats)

$date = new DateTime('first day of previous month 00:00:00', new DateTimeZone('UTC'));
var_dump($date->format('Y-m-d H:i:s')); // string(19) "2013-11-01 00:00:00"

$date = new DateTime('first day of previous month 00:00:00', new DateTimeZone('Europe/Amsterdam'));
var_dump($date->format('Y-m-d H:i:s')); // string(19) "2013-11-01 00:00:00"

Or add midnight (Relative Formats)

$date = new DateTime('midnight first day of previous month', new DateTimeZone('Europe/Amsterdam'));
var_dump($date->format('Y-m-d H:i:s'));

$date = new DateTime('midnight first day of previous month', new DateTimeZone('UTC'));
var_dump($date->format('Y-m-d H:i:s'));

Demo.

like image 141
sectus Avatar answered Nov 19 '22 07:11

sectus