Added recipe for parsing daylight transition times

Tai Meng
2016-11-07 12:22:22 -08:00
parent 0a0fc0c72f
commit 4e10f69125

@@ -27,6 +27,7 @@ This page contains examples and recipes contributed by community members. Feel f
- [How to convert to/from QDate](#QDate)
- [How to convert to/from Windows' FILETIME](#FILETIME)
- [Print out a compact calendar for the year](#calendar)
- [Parsing unambiguous date time inside daylight transition](#parse_daylight_transition)
***
@@ -1563,6 +1564,49 @@ which outputs:
26 27 28 29 30 24 25 26 27 28 29 30 28 29 30 26 27 28 29 30 31
31
<a name="parse_daylight_transition"></a>
### Parsing unambiguous date time inside daylight transition
(by [Tai Meng](https://github.com/ta1meng))
We needed the ability to (de)serialize date time values. We investigated how we could parse an input string that looks like this:
1) 1999-10-31 01:30:00 US/Pacific PST
After consulting [Howard](https://github.com/HowardHinnant), we learned that the input string should instead look like this:
2) 1999-10-31 01:30:00 -08:00 US/Pacific
and then the solution is simple. To convert PST to -08:00 is in general non-trivial and often requires user input, because abbreviations often match multiple timezones. This recipe assumes that users of this recipe will have a way to re-format strings of form 1) into strings of form 2).
Once we have a string of form 2), give this sample code a try (thank you [Aaron](https://github.com/ahn6) who provided the draft):
#include <iostream>
#include <sstream>
#include <string>
#include "tz.h"
void main()
{
using namespace std;
using namespace date;
istringstream inputStream{ "1999-10-31 01:30:00 -08:00 US/Pacific" };
// Using local_seconds would resolve in ambiguous date exception
sys_seconds tp;
string tz_name;
parse(inputStream, "%F %T %Ez %Z", tp, tz_name);
// bool operator tells us whether stream was successfully parsed
assert(bool(inputStream));
auto zt = make_zoned(tz_name, tp);
// This will output America/Los_Angeles, because US/Pacific is an alias of it.
cout << format("%F %T %Ez", zt) << ' ' << zt.get_time_zone()->name() << '\n';
}
***
![CC BY Logo](http://mirrors.creativecommons.org/presskit/buttons/80x15/svg/by.svg) _This work is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/)._