1. Trang chủ
  2. » Công Nghệ Thông Tin

Giải pháp thiết kế web động với PHP - p 43 pps

10 240 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 594,24 KB

Nội dung

FORMATTING TEXT AND DATES 401 The DateTime() constructor also takes two optional arguments: a string containing a date and/or time, and a DateTimeZone object. The date/time string for the first argument can be in any of the formats listed at http://docs.php.net/manual/en/datetime.formats.php. Unlike MySQL, which accepts only one format, PHP goes to the opposite extreme. The range of valid formats is overwhelming and potentially confusing. For example, to create a DateTime object for Christmas Day 2010, all the following formats are valid: '12/25/2010' '25-12-2010' '25 Dec 2010' 'Dec 25 2010' '25-XII-2010' '25.12.2010' '2010/12/25' '2010-12-25' 'December 25th, 2010' This is not an exhaustive list. Its just a selection of valid formats. Where the potential confusion arises is in the use of separators. For example, the forward slash is permitted in American-style (12/25/2010) and ISO (2010/12/25) dates, but not when the date is presented in European order or when the month is represented by Roman numerals. To present the date in European order, the separator must be a dot, tab, or dash. Dates can also be specified using relative expressions, such as “next Wednesday,” “tomorrow,” or “last Monday.” However, theres potential for confusion here, too. Some people use “next Wednesday” to mean “Wednesday next week.” PHP interprets the expression literally. If today is Tuesday, “next Wednesday” means the following day. This situation offers great flexibility—as long as you know where your date and time information is coming from, and it conforms to one of the many valid formats. PHP 5.3 expanded this flexibility even further by introducing a method that allows you to specify a custom format for creating a DateTime object. Its described after the next section because the same technique is used for specifying both output and input formats. You cant use echo on its own to display the value stored in a DateTime object. In addition to echo, you need to tell PHP how to format the output using the format() method. Formatting dates in PHP The DateTime classs format() method uses the same format characters as the original date() function. Although this makes for continuity, the format characters are often difficult to remember and seem to have no obvious reasoning behind them. Table 14-4 lists the most useful date and time format characters. The DateTime class and date() function display the names of weekdays and months in English only, but the strftime() function uses the language specified by the servers locale. So, if the servers locale is set to Spanish, a DateTime object and date() display Saturday, but strftime() displays sábado. In CHAPTER 14 402 addition to the format characters used by the DateTime class and the date() function, Table 14-4 lists the equivalent characters used by strftime(). Table 14-4. The main date and time format characters Unit DateTime/date() strftime() Description Example Day d %d Day of the month with leading zero 01 through 31 j %e* Day of the month without leading zero 1 through 31 S English ordinal suffix for day of the month st, nd, rd, or th D %a First three letters of day name Sun, Tue l (lowercase “L”) %A Full name of day Sunday, Tuesday Month m %m Number of month with leading zero 01 through 12 n Number of month without leading zero 1 through 12 M %b First three letters of month name Jan, Jul F %B Full name of month January, July Y %Y Year displayed as four digits 2006 Year y %y Year displayed as two digits 06 g Hour in 12-hour format without leading zero 1 through 12 h %I Hour in 12-hour format with leading zero 01 through 12 G Hour in 24-hour format without leading zero 0 through 23 Hour H %H Hour in 24-hour format with leading zero 01 through 23 Minutes i %M Minutes with leading zero if necessary 00 through 59 Seconds s %S Seconds with leading zero if necessary 00 through 59 AM/PM a %p Lowercase am AM/PM A Uppercase PM * Note: %e is not supported on Windows. Download from Wow! eBook <www.wowebook.com> FORMATTING TEXT AND DATES 403 You can combine these format characters with punctuation to display the current date in your web pages according to your own preferences. To format a DateTime object, pass the format string as an argument to the format() method like this (the code is in date_format_01.php in the ch14 folder): <?php $now = new DateTime(); $xmas2010 = new DateTime('12/25/2010'); ?> <p>It's now <?php echo $now->format('g.ia'); ?> on <?php echo  $now->format('l, F jS, Y'); ?></p> <p>Christmas 2010 falls on a <?php echo $xmas2010->format('l'); ?></p> In this example, two DateTime objects are created: one for the current date and time, and the other for December 25, 2010. Using the format characters from Table 14-4, various date parts are extracted from the two objects, producing the output shown in the following screenshot: The code in date_format_02.php produces the same output using the date() and strtotime() functions like this: <?php $xmas2010 = strtotime('12/25/2010'); ?> <p>It's now <?php echo date('g.ia'); ?> on <?php echo date('l, F jS, Y'); ?></p> <p>Christmas 2010 falls on a <?php echo date('l', $xmas2010); ?></p> The first line uses strtotime() to create a timestamp for December 25, 2010. Theres no need to create a timestamp for the current date and time, because date() defaults to them when used without a second argument. If the timestamp for Christmas Day isnt used elsewhere in the script, the first line can be omitted, and the last call to date() can be rewritten like this (the code is in date_format_03.php): echo date('l', strtotime('12/25/2010')); Creating a DateTime object from a custom format In PHP 5.3 and later, you can specify a custom input format for a DateTime object using the format characters in Table 14-4. Instead of creating the object with the new keyword, you use the createFromFormat() static method like this: $date = DateTime::createFromFormat( format_string , input_date , timezone ); The third argument, timezone , is optional. If included, it should be a DateTimeZone object. CHAPTER 14 404 A static method belongs to the whole class, rather than to a particular object. You call a static method using the class name followed by a double colon and the method name. The double colon is called the scope resolution operator. You first used it to call the parent constructor in “Extending a class” in Chapter 8. Internally, its called PAAMAYIM_NEKUDOTAYIM , which is Hebrew for “double colon.” Why Hebrew? Because the Zend Engine that powers PHP was originally developed by Zeev Suraski and Andi Gutmans when they were students at the Technion – Israel Institute of Technology. Apart from earning points in a geek trivia quiz, knowing the meaning of PAAMAYIM_NEKUDOTAYIM could save you a lot of head scratching when you see it in a PHP error message. For example, you can use the createFromFormat() method to accept a date in the European format of day, month, year separated by slashes like this (the code is in date_format_04.php): $xmas2010 = DateTime::createFromFormat('d/m/Y', '25/12/2010'); echo $xmas2010->format('l, jS F Y'); This produces the following output: Attempting to use 25/12/2010 as the input to the DateTime constructor triggers a fatal error. If you want to use a format not supported by the DateTime constructor, you must use the createFromFormat() static method. Although the createFromFormat() method is useful, it can be used only in circumstances where you know the date will always be in a specific format. Its also important to note that it does not work in PHP 5.2. Choosing between date() and the DateTime class When it comes to displaying a date, its always a two-step process with the DateTime class. You need to instantiate the object before you can call the format() method. With the date() function, you can do it in a single pass. Since they both use the same format characters, date() wins hands down when dealing with the current date and/or time. For simple tasks like displaying the current date, time, or year, use date(). Where the DateTime class comes into its own is when working with date-related calculations and time zones using the methods listed in Table 14-5. Note that some methods are supported only in PHP 5.3 and later. FORMATTING TEXT AND DATES 405 Table 14-5. The main DateTime methods Method Arguments Description Since PHP 5.2 format() Format string Formats the date/time using the format characters in Table 14-4. getOffset() None Returns the time zone offset from UTC expressed in seconds. getTimezone() None Returns a DateTimeZone object representing the DateTime objects time zone. modify() Relative date string Changes the date/time using a relative expression, such as '+2 weeks'. setDate() Year, month, day Changes the date. The arguments should be separated by commas. Months or days in excess of the permitted range are added to the resulting date. For example, using 14 as the month sets the date to February of the following year. setTime() Hours, minutes, seconds Resets the time. Arguments are comma- separated values. Seconds are optional. Values in excess of the permitted range are added to the resulting date/time. For example, setting the hour to 26 results in 2am on the following day. setTimezone() DateTimeZone object Changes the time zone. Since PHP 5.3 add() DateInterval object Increments the date/time by the set period. sub() DateInterval object Deducts the set period from the date/time. diff() DateTime object, Boolean Returns a DateInterval object representing the difference between the current DateTime object and the one passed as an argument. The optional second argument determines whether to convert negative values to their positive equivalent. The default is false. CHAPTER 14 406 Method Arguments Description getTimestamp() None Returns the Unix timestamp for the date/time. setTimestamp() Unix timestamp Sets the date/time according to the Unix timestamp. As Table 14-5 explains, adding out-of-range values with setDate() and setTime() results in the excess being added to the resulting date or time. The same happens with the modify(), add(), and sub() methods. For example, if you add one month to a DateTime object that represents January 31, 2011, the resulting value is not the last day of February, but March 3. This is because adding one month to the original date results in February 31, but February has only 28 days in a non-leap year. So, the out-of-range value is added to the month, resulting in March 3. If you subsequently subtract one month from the same DateTime object, it brings you back to February 3, not to the original starting date. The following code in date_modify.php in the ch14 folder illustrates this point: <?php $format = 'F j, Y'; $date = new DateTime('January 31, 2011'); ?> <p>Original date: <?php echo $date->format($format); ?>.</p> <p>Add one month: <?php $date->modify('+1 month'); echo $date->format($format); $date->modify('-1 month'); ?> <p>Subtract one month: <?php echo $date->format($format); ?> This produces the output shown in Figure 14-9. Figure 14-9. Adding and subtracting months can lead to unexpected results. The modify() method uses ordinary text expressions to add or subtract a set period. The add(), sub(), and diff() methods added in PHP 5.3 can be used only with DateInterval objects, which are described later in this chapter. FORMATTING TEXT AND DATES 407 Using the DateTimeZone class A DateTime object automatically uses the web servers default time zone unless you have reset the time zone using one of the methods described earlier. However, you can set the time zone of individual DateTime objects through the optional second argument of the constructor or by using the setTimezone() method. In both cases, the argument must be a DateTimeZone object. To create a DateTimeZone object, pass the constructor one of the supported time zones listed at http://docs.php.net/manual/en/timezones.php like this: $UK = new DateTimeZone('Europe/London'); $USeast = new DateTimeZone('America/New_York'); $Hawaii = new DateTimeZone('Pacific/Honolulu'); When checking the list of supported time zones, its important to realize that theyre based on geographic regions and cities, rather than official time zones. This is because PHP automatically takes account of daylight saving time. Arizona, which doesnt use daylight saving time, is covered by America/Phoenix. The organization of time zones into geographic regions produces some surprises. America doesnt mean the United States of America, but the continents of North and South America and the Caribbean. As a result, Honolulu is not listed in America, but as a Pacific time zone. Europe also means the European continent, including the British Isles but excluding other islands. So, Reykjavik and Madeira are listed as Atlantic time zones, and the Norwegian island of Longyearbyen has the exclusive privilege of being the only Arctic time zone. The code in timezones.php creates DateTimeZone objects for London, New York, and Honolulu, and then initializes a DateTime object using the first one like this: $now = new DateTime('now', $UK); After displaying the date and time using echo and the format() method, the time zone is changed using the setTimezone() method like this: $now->setTimezone($USeast); The next time $now is displayed, it shows the date and time in New York. Finally, setTimezone() is used again to change the time zone to Honolulu, producing the following output: To find the time zone of your server, you can either check php.ini or use the getTimezone() method with a DateTime object. The getTimezone() method returns a DateTimeZone object, not a string containing the time zone. To get the value of the time zone, you need to use the DateTimeZone objects getName() method like this (the code is in timezone_display.php): CHAPTER 14 408 $now = new DateTime(); $timezone = $now->getTimezone(); echo $timezone->getName(); The DateTimeZone class has several other methods that expose information about a time zone. For the sake of completeness, theyre listed in Table 14-6, but the main use of the DateTimeZone class is to set the time zone for DateTime objects. Table 14-6. DateTimeZone methods Method Arguments Description getLocation() None Returns an associative array containing the country code, latitude, longitude, and comments about the time zone. Requires PHP 5.3 or later. getName() None Returns a string containing the geographic area and city of the time zone. getOffset() DateTime object Calculates the offset from UTC (in seconds) of the DateTime object passed as an argument. getTransitions() Start, end (5.3+) Returns a multidimensional array containing historical and future dates and times of switching to and from daylight saving time. Takes no arguments in PHP 5.2. Since PHP 5.3, accepts two timestamps as optional arguments to limit the range of results. listAbbreviations() None Generates a large multidimensional array containing the UTC offsets and names of time zones supported by PHP. listIdentifiers() DateTimeZone constant, country code (5.3+) Returns an array of all PHP time zone identifiers, such as Europe/London, America/New_York, and so on. Takes no arguments in PHP 5.2. Since PHP 5.3, accepts two optional arguments to limit the range of results. Use as the first argument one of the DateTimeZone constants listed at http://docs.php.net/manual/en/class. datetimezone.php. If the first argument is DateTimeZone::PER_COUNTRY, a two-letter country code can be used as the second argument. The last two methods in Table 14-6 are static methods. Call them directly on the class using the scope resolution operator like this: $abbreviations = DateTimeZone::listAbbreviations(); Adding and subtracting set periods with the DateInterval class The DateInterval class was introduced in PHP 5.3 and is required to specify the period to be added or subtracted from a DateTime object using the add() and sub() methods. Its also used by the diff() FORMATTING TEXT AND DATES 409 method, which returns a DateInterval object. Using the DateInterval class feels rather odd to begin with, but its relatively simple to understand. The DateInterval class and the associated DateTime methods do not work in PHP 5.2. To create a DateInterval object, you need to pass to the constructor a string that specifies the length of the interval formatted according to the ISO 8601 standard. The string always begins with the letter P (for period), followed by one or more pairs of integers and letters known as period designators. If the interval includes hours, minutes, or seconds, the time element is preceded by the letter T. Table 14-7 lists the valid period designators. Table 14-7. ISO 8601 period designators used by the DateInterval class Period Designator Meaning Y Years M Months W Weeks—cannot be combined with days D Days—cannot be combined with weeks H Hours M Minutes S Seconds The following examples should clarify how to specify an interval: $interval1 = new DateInterval('P2Y'); // 2 years $interval2 = new DateInterval('P5W'); // 5 weeks $interval3 = new DateInterval('P37D'); // 5 weeks 2 days $interval4 = new DateInterval('PT6H20M'); // 6 hours 20 minutes $interval5 = new DateInterval('P1Y2DT3H5M50S'); // 1 year 2 days 3 hours 5 min // 50 sec Note that $interval3 needs to specify the total number of days, because weeks are automatically converted to days, so W and D cannot be combined in the same interval definition. To use a DateInterval object with the add() or sub() method of the DateTime class, pass the object as an argument. For example, this adds 12 days to the date for Christmas Day 2010: $xmas2010 = new DateTime('12/25/2010'); $interval = new DateInterval('P12D'); $xmas2010->add($interval); CHAPTER 14 410 If you dont need to reuse the interval, you can pass the DateInterval constructor directly as the argument to add() like this: $xmas2010 = new DateTime('12/25/2010'); $xmas2010->add(new DateInterval('P12D')); The result of this calculation is demonstrated in date_interval_01.php, which produces the following output: An alternative to using the period designators listed in Table 14-7 is to use the static createFromDateString() method, which takes as an argument an English relative date string in the same way as strtotime(). Using createFromDateString(), the preceding example can be rewritten like this (the code is in date_interval_02.php): $xmas2010 = new DateTime('12/25/2010'); $xmas2010->add(DateInterval::createFromDateString('+12 days')); This produces exactly the same result. Adding and subtracting months with DateInterval has the same effect as described earlier. If the resulting date is out of range, the extra days are added. For example, adding one month to January 31 results in March 3 or 2, depending on whether its a leap year. Finding the difference between two dates with the diff() method To find the difference between two dates, create a DateTime object for both dates, and pass the second object as the argument to the first objects diff() method. The result is returned as a DateInterval object. To extract the result from the DateInterval object, you need to use the objects format() method which uses the format characters listed in Table 14-8. These are different from the format characters used by the DateTime class. Fortunately, most of them are easy to remember. Table 14-8. Format characters used by the DateInterval format() method Format character Description Examples %Y Years. At least two digits, with leading zero if necessary. 12, 01 %y Years, no leading zero 12, 1 %M Months with leading zero 02, 11 . '12/25/2010' '2 5-1 2-2 010' '25 Dec 2010' 'Dec 25 2010' '25-XII-2010' '25.12.2010' '2010/12/25' '201 0-1 2-2 5'. < ?php $xmas2010 = strtotime('12/25/2010'); ?> < ;p& gt;It's now < ?php echo date('g.ia'); ?> on < ?php echo date('l, F jS, Y'); ?>< /p& gt;. < ?php echo  $now->format('l, F jS, Y'); ?>< /p& gt; < ;p& gt;Christmas 2010 falls on a < ?php echo $xmas201 0-& gt;format('l'); ?>< /p& gt; In this example,

Ngày đăng: 06/07/2014, 19:20

w