Development

Date and Time – PHP way – part 1

Usually, when we speak about date and time, we think about date, time or gmdate (or many other names) functions and that is all right, we’ve got them and it works. But some of you may not be aware about DateTime class, built in PHP (since version 5.2 as far as I remember).

First, the constructor. It can get two parameters – time and timezone. You may omit those two parameters, then time will be set to ‘now’ and timezone will be set to null. What does it mean? It will give you current time in your default timezone (default for the server of course). You may also get current time in different timezone, then you must set time as null and timezone to desired time zone of course.

What is returned? No surprise here… DateTime object! If the time format is unrecognizable by the class, exception is thrown (since PHP5.3, previously it was standard error). All right, we’ve got DateTime object, what to do next? Well, it depends. First, let’s see this object:

What should we get? It depends, of course. I live in Europe/Warsaw time zone so I got something like this:


What is timezone_type? Nothing very important for us, it’s just a method of storing time zone. Type 1 means UTC offset, something like “27 June 2017 +0100”, type 2 means timezone abbreviation, like “CET” at the end of the string (“27 June 2017 CET”) and type 3 stands for identifier such as “Europe/Warsaw” (like in this example).

Hey, there is still a question, what next? Ok, ok. We must know a bit before we can start. Around DateTime class there are a few more classes. First example – DateTimeZone class. How to use it? Well, let’s write something like this:

Our results:

Now we know the difference. What’s next?
Well, there is a lot.

If we need to convert weird date/time formats… nothing better than DateTime class! Well, let’s say our date/time format is: day, month (with dots), year, slash, hour, minute, second (with dashes). Something like this:
6. 11. 2017/22-15-30 – it is for 6th Nov 2017, 22:15:30. Write something like this:

It works! We’ve got:

To be continued.

Leave a Reply

Your email address will not be published. Required fields are marked *