Join Kevin Skoglund for an in-depth discussion in this video Formatting dates and times: Strings and SQL, part of PHP with MySQL Beyond the Basics.
In this movie, we're going to continue looking at dates and times. In the last movie we saw how to build a Unix timestamp, and in this movie I want us to take a look at how we can format that Unix timestamp. There are two functions that are going to allow us to do that. The first function is date and the second is strf time. Now, you can either pronounce that string for time, string format time, but the idea is that we're taking a timestamp and turning it into a string. So in both cases we're going to be formatting a Unix timestamp into something that's human-readable, like November 13, 2005, instead of however many seconds it has been since 1970.
That's not very user-friendly. You will see that each of these functions takes a timestamp as a second argument. That timestamp is just a simple Unix timestamp, we can take any timestamp we have created and drop it into that second argument. It's the format that's the tricky part and that we're going to have to learn more about. In fact, the functions may look identical but what differentiates them is the format. Each function has its own format rules. Let's take a look at date first. The easiest way to show you the formatting options for date is to take a look at the http://www.php.net page for date. Go to http://www.php.net and do a search for date and you will get this page. Here are the different formats for the output string. Scroll down.
Notice the format characters over here, d, D, j, and so on, and it tells you what each code does. So, for example, d is the day of the month, two digits with leading zeros, such as 01 to 31. You will notice that j is also the day of the month, but without leading zeros, 1 to 31. D is a textual representation of a day, the three letters, Monday through Sunday, so Wed for Wednesday, for example. Now, we can scroll down a bit further on the page to see how these strings are used. The format is a simple string but with the format characters as placeholders for each part of the date. When the date function is called, it will replace the format code placeholders with the actual data.
So for example, this format string here will return the line right above it. Monday 8th of August 2005 and then the time. Now, in this example they are not passing in a timestamp, so it defaults to the current time. But in the example below that, you can see that they do pass in the timestamp as a second argument. They build the timestamp using mktime and then pass it in. Notice also that the format code that they are using in that second one is just simply an L, and that's it. If we go and look at L, you will see what it does is it returns the day of the week. So this will tell you what day of the week July 1t 2000 is. That's a nice little trick. Not only are we able to format the date in something human-readable, we're actually able to find out some information about the calendar as well.
Now personally, I don't use date and I would recommend that you also use string for time instead. The reason why I like it better is that its part of the Unix Open Standard and it's used by many programming languages, besides PHP, and has support for formatting dates in foreign languages as well. So let's take a look at the string for time format codes to see how they are different from the ones for date. So for example, if we look here at %d, you will see that there is a % in front to it, first of all. The % helps make it clear that this is a format code. So all the string for time ones are going to be proceeded by % sign before the code. So essentially %d does the same thing that d did in the date function.
But now take a look at %D. You will see that this is different. Instead of being the three-letter code for the day of the week, it's going to be a shortcut for the month, day, and year as numbers with slashes in between them. Instead, if we look at %a up here, you will see that that is the abbreviated weekday name. So that's how we get that same functionality we had before. So some of them are going to be the same. %m for example down here, the month as a decimal number. That's the same. But %M and other ones like that are not. So there is a lot of differences. So you really have to learn each set of code separately, and that's why I think you ought to pick one and stick with it, and I recommend you go with the string for time (strftime).
Now obviously, this list here of codes on the string for time is a comprehensive list, and you may want to copy down the ones that you are going to use most often and make yourself a little cheat sheet. But you will also get familiar pretty quickly with them and you will be able to remember the ones when you need it. So let's try this out now. I have still got my old window open for date_time_unix. Let's go ahead and do File > Save As on that, and we'll call this one instead date_time_format.php, and I'll just change it up here to say Formatting, and then we'll go ahead and clear up all the PHP we had there so we can start fresh.
So the first thing I'll do is I'll just build a real simple timestamp with the current time. And we know how to do that with just time. Then let's make ourselves echo back the result of strftime, and we'll say, "The date today is" and let's put in our format code, so %m. So the % sign lets it know it's a code for strftime, and then the m tells it that it will be the numbers for the month, and then we'll have %d/%y. Then last of all we need to pass in of course our timestamp.
Let's go back over to our browser and try that out. Instead of loading up Unix, I load up format.php. There you go. So today is November 1 2008. Now, today is not actually November 1 for me. Instead I set my system clock to that time so that I could show you something. Now, earlier I pointed out the reasons why I like strftime better than date. There is one feature that date has that strftime doesn't. Date has options for leaving off the leading zeros before a month or a day number. Notice here I have got the 01. That's the leading zero that I'm talking about in front of it.
We kept the option to leave that off in date and it could just simply be 11/1/08. The same thing would be true if we were talking about January, string for time would print as 01, whereas in date we have the option of leaving the leading zero off. A lot of times we're going to want to get rid of those leading zeros. So I'm going to show you how you can do that by writing yourself a helper function. It's a little bit of a hack but it is effective. So what we'll do here is we'll just take this line and we'll copy it down here, and instead of just sending in the formatting, we're going to put an asterisk in front of each of these two. Those are the two places where a zero may show up. So we're sort of marking the position where we want to watch for a zero, and we're doing that with this asterisk. Now, you can use any character you want.
I picked the asterisk because it's something that I don't use very often when I'm formatting this kind of date, but you could easily use a different character if you needed the asterisk for another reason. So now let's write ourselves a helper function, function strip_zeros_from_date, and then we'll pass in $marked_string=, and there we go, we'll pass in a empty string by default. The first step is that we're going to remove the marked zeros. So $no_zeros will be equal to str _replace, and we'll use string replace (str_replace) to look for every occurrence of an asterisk with a zero, and if we find it, eliminate both, get them both out of there. Then we'll just need to pass in the marked_string so it knows what to search through.
Then once we do that, the last step is we'll remove any remaining marks, because we don't want to have to deal with a case where we have something like December, which would not have a leading zero, and so we would still have that asterisk sitting there because it didn't get removed. So we'll then do another step, $ cleaned_string =, and we'll do another str_replace. But this time we're going to be looking for any asterisk that's still left around and we'll replace that with nothing, and we'll do that to our no_zeros string. Finally, return back that cleaned value.
So there we go. Now we have a function that should work for us. Let's just move this strftime down below the function so that it's defined. We'll just put it around the whole thing. There we go. I'll save it, and let's come back over. Let's try it out. There we are. It didn't put a br tag in there but you can see this one does have the 01. This one did remove the 01. So most of my PHP projects I go ahead and just put it in a function like this that will help me to use strftime and to be able to get rid of those zeros, and I think it might be helpful to you too.
The very last thing I want to show you here is that I can also format strings suitable for storage in MySQL. A lot of people wonder how you do this conversion. You don't want to just pass in a Unix timestamp to MySQL; you want to format it to something that MySQL can understand. Luckily it's very, very easy to do. Let's do echo "<hr />" just to make a nice break there, and then we'll do a new $dt = time;. That will be dt for date time. Then what we want to get is $mysql_ datetime, and the way we're going to do that is using that strftime function and we're going to put in the following formatting code. %Y, that's the year with all four digits, and then %m, %d, then a space, %H for the hour, %M for the minute, and %S for the second. There we go, and then of course we'll want to pass in that time we were just working with. So we could pass in any timestamp, and we're going to have it output with this formatting. That will go into this mysql_datetime. Of course, if we want to see the results of that, then we'll just need to do an echo on it. There we go.
So we'll come back and there we are. That's the format that MySQL understands. So go ahead and write down those formatting codes. Make sure that you keep them handy for working with MySQL. But you also may want to just make a copy of this here, just to show you what the result should be, in case you end up using date or some other system, whatever, this is the format that MySQL wants for date, time fields. Now, if is the date field, it will just be the date part of that, but this is the format it's going to use. So now that we have learned to work with and format the dates and times, we're ready to move on. In the next movie we're going to look at server and request variables.
- Defining and using classes, methods, and attributes
- Understanding class inheritance and access modifiers
- Working with files and directories
- Uploading files to a server via forms
- Sending emails with PHP
- Using pagination and View templates
Skill Level Intermediate
Q: When I try to launch phpMyAdmin in WAMP, I get the following error:
#1045 - Access denied for user 'root'@'localhost' (using password: NO).
How can I fix this problem?
Q: This course was updated on 03/19/2015. What changed?
A: We updated several movies to use the newer MySQL database adapter (mysqli) and added a new movie on late static binding in chapter six, "Foundations of an OOP Project."