Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

13.3. Writing and Reading Dates and Times

Problem

You need to display or read dates and times using local formatting conventions.

Solution

Use the time_t type and tm struct from <ctime>, and the date and time facets provided in <locale>, to write and read dates and times (facets are described in the discussion in a moment). See Example 13-4 for a sample.

Example 13-4. Writing and reading dates

#include <iostream> #include <ctime> #include <locale> #include <sstream> #include <iterator> using namespace std; void translateDate(istream& in, ostream& out) { // Create a date reader const time_get<char>& dateReader = use_facet<time_get<char> >(in.getloc()); // Create a state object, which the facets will use to tell // us if there was a problem. ios_base::iostate state = 0; // End marker istreambuf_iterator<char> end; tm t; // Time struct (from <ctime>) // Now that all that's out of the way, read in the date from // the input stream and put it in a time struct. dateReader.get_date(in, end, in, state, &t); // Now the date is in a tm struct. Print it to the out stream // using its locale. Make sure you only print out what you // know is valid in t. if (state == 0 || state == ios_base::eofbit) { // The read succeeded. const time_put<char>& dateWriter = use_facet<time_put<char> >(out.getloc()); char fmt[] = "%x"; if (dateWriter.put(out, out, out.fill(), &t, &fmt[0], &fmt[2]).failed()) cerr << "Unable to write to output stream.\n"; } else { cerr << "Unable to read cin!\n"; } } int main() { cin.imbue(locale("english")); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page