Reputation: 233
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?
Upvotes: 10
Views: 5003
Reputation: 15454
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.
Upvotes: 19