Ticket #17932: test.cpp

File test.cpp, 1.7 KB (added by fatigatti, 21 months ago)

Simple strptime test

Line 
1#include <cstdio>
2#include <cstring>
3#include <ctime>
4
5// The formats used should be, in order of preference (according to RFC2616,
6// section 3.3):
7// RFC1123 / RFC822: "Sun, 06 Nov 1994 08:49:37 GMT"
8// RFC1036 / RFC850: "Sunday, 06-Nov-94 08:49:37 GMT"
9// asctime : "Sun Nov 6 08:49:37 1994"
10//
11// RFC1123 is the preferred one because it has 4 digit years.
12//
13// But of course in real life, all possible mixes of the formats are used.
14// Believe it or not, it's even possible to find some website that gets this
15// right and use one of the 3 formats above.
16// Often seen variants are:
17// - RFC1036 but with 4 digit year,
18// - Missing or different timezone indicator
19// - Invalid weekday
20static const char* kDateFormats[] = {
21 // RFC1123
22 "%a, %d %b %Y %H:%M:%S", // without timezone
23 "%a, %d %b %Y %H:%M:%S GMT", // canonical
24
25 // RFC1036
26 "%A, %d-%b-%y %H:%M:%S", // without timezone
27 "%A, %d-%b-%y %H:%M:%S GMT", // canonical
28
29 // RFC1036 with 4 digit year
30 "%a, %d-%b-%Y %H:%M:%S", // without timezone
31 "%a, %d-%b-%Y %H:%M:%S GMT", // with 4-digit year
32 "%a, %d-%b-%Y %H:%M:%S UTC", // "UTC" timezone
33
34 // asctime
35 "%a %d %b %H:%M:%S %Y"
36};
37
38static const char* example = "Mon, 5 Sep 2022 14:14:14 GMT";
39
40// Main function
41int main(void)
42{
43 struct tm expireTime;
44
45 memset(&expireTime, 0, sizeof(struct tm));
46
47 int fDateFormat = -1;
48 unsigned int i;
49 for (i = 0; i < sizeof(kDateFormats) / sizeof(const char*);
50 i++) {
51 const char* result = strptime(example, kDateFormats[i],
52 &expireTime);
53 printf("Parsing %s\n", example);
54 printf("Year %d, hour %d\n", expireTime.tm_year, expireTime.tm_hour);
55
56 if (result != NULL) {
57 printf("Match!\n");
58 fDateFormat = i;
59 break;
60 }
61 }
62
63 if (fDateFormat == -1)
64 printf("Did not match\n");
65}
66