Chapter 11. Working with Dates and Times

Working with dates and times should be simple, but it’s not. Regardless of whether you’re writing a shell script or a much larger program, time keeping is full of complexities: different formats for displaying the time and date, Daylight Saving Time, leap years, leap seconds, and all of that. For example, imagine that you have a list of contracts and the dates on which they were signed. You’d like to compute expiration dates for all of those contracts. It’s not a trivial problem: does a leap year get in the way? Is it the sort of contract where daylight saving time is likely to be a problem? And how do you format the output so that it’s unambiguous? Does 7/4/07 mean July 4, 2007, or does it mean April 7?

Dates and times permeate every aspect of computing. Sooner or later you are going to have to deal with them: in system, application, or transaction logs; in data processing scripts; in user or administrative tasks; and more. This chapter will help you deal with them as simply and cleanly as possible. Computers are very good at keeping time accurately, particularly if they are using the Network Time Protocol (NTP) to keep themselves synced with national and international time standards. They’re also great at understanding the variations in Daylight Saving Time from locale to locale. To work with time in a shell script, you need the Unix date command (or even better, the GNU version of the date command, which is standard on Linux). date is capable ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.