blob: 10ca1665667c9e7cfb47a0c5afae69fe3b507445 [file] [log] [blame]
Mike Lockwood16864ba2010-05-11 17:16:59 -04001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mike Lockwood335dd2b2010-05-19 10:33:39 -040017#include <stdio.h>
Mike Lockwood16864ba2010-05-11 17:16:59 -040018#include <time.h>
19
20#include <cutils/tztime.h>
21#include "MtpUtils.h"
22
Mike Lockwood7850ef92010-05-14 10:10:36 -040023namespace android {
24
Mike Lockwood16864ba2010-05-11 17:16:59 -040025/*
26DateTime strings follow a compatible subset of the definition found in ISO 8601, and
27take the form of a Unicode string formatted as: "YYYYMMDDThhmmss.s". In this
28representation, YYYY shall be replaced by the year, MM replaced by the month (01-12),
29DD replaced by the day (01-31), T is a constant character 'T' delimiting time from date,
30hh is replaced by the hour (00-23), mm is replaced by the minute (00-59), and ss by the
31second (00-59). The ".s" is optional, and represents tenths of a second.
32*/
33
34bool parseDateTime(const char* dateTime, time_t& outSeconds) {
35 int year, month, day, hour, minute, second;
36 struct tm tm;
37
38 if (sscanf(dateTime, "%04d%02d%02dT%02d%02d%02d",
39 &year, &month, &day, &hour, &minute, &second) != 6)
40 return false;
41 const char* tail = dateTime + 15;
42 // skip optional tenth of second
43 if (tail[0] == '.' && tail[1])
44 tail += 2;
45 //FIXME - support +/-hhmm
46 bool useUTC = (tail[0] == 'Z');
47
48 // hack to compute timezone
49 time_t dummy;
50 localtime_r(&dummy, &tm);
51
52 tm.tm_sec = second;
53 tm.tm_min = minute;
54 tm.tm_hour = hour;
55 tm.tm_mday = day;
56 tm.tm_mon = month;
57 tm.tm_year = year - 1900;
58 tm.tm_wday = 0;
59 tm.tm_isdst = -1;
60 if (useUTC)
61 outSeconds = mktime(&tm);
62 else
63 outSeconds = mktime_tz(&tm, tm.tm_zone);
64
65 return true;
66}
67
68void formatDateTime(time_t seconds, char* buffer, int bufferLength) {
69 struct tm tm;
70
71 localtime_r(&seconds, &tm);
72 snprintf(buffer, bufferLength, "%04d%02d%02dT%02d%02d%02d",
73 tm.tm_year + 1900, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
74}
75
Mike Lockwood7850ef92010-05-14 10:10:36 -040076} // namespace android