MtpUtils.cpp revision 7850ef999740f214a1990a9c090d3f3865d435aa
1/* 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 17#include <time.h> 18 19#include <cutils/tztime.h> 20#include "MtpUtils.h" 21 22namespace android { 23 24/* 25DateTime strings follow a compatible subset of the definition found in ISO 8601, and 26take the form of a Unicode string formatted as: "YYYYMMDDThhmmss.s". In this 27representation, YYYY shall be replaced by the year, MM replaced by the month (01-12), 28DD replaced by the day (01-31), T is a constant character 'T' delimiting time from date, 29hh is replaced by the hour (00-23), mm is replaced by the minute (00-59), and ss by the 30second (00-59). The ".s" is optional, and represents tenths of a second. 31*/ 32 33bool parseDateTime(const char* dateTime, time_t& outSeconds) { 34 int year, month, day, hour, minute, second; 35 struct tm tm; 36 37 if (sscanf(dateTime, "%04d%02d%02dT%02d%02d%02d", 38 &year, &month, &day, &hour, &minute, &second) != 6) 39 return false; 40 const char* tail = dateTime + 15; 41 // skip optional tenth of second 42 if (tail[0] == '.' && tail[1]) 43 tail += 2; 44 //FIXME - support +/-hhmm 45 bool useUTC = (tail[0] == 'Z'); 46 47 // hack to compute timezone 48 time_t dummy; 49 localtime_r(&dummy, &tm); 50 51 tm.tm_sec = second; 52 tm.tm_min = minute; 53 tm.tm_hour = hour; 54 tm.tm_mday = day; 55 tm.tm_mon = month; 56 tm.tm_year = year - 1900; 57 tm.tm_wday = 0; 58 tm.tm_isdst = -1; 59 if (useUTC) 60 outSeconds = mktime(&tm); 61 else 62 outSeconds = mktime_tz(&tm, tm.tm_zone); 63 64 return true; 65} 66 67void formatDateTime(time_t seconds, char* buffer, int bufferLength) { 68 struct tm tm; 69 70 localtime_r(&seconds, &tm); 71 snprintf(buffer, bufferLength, "%04d%02d%02dT%02d%02d%02d", 72 tm.tm_year + 1900, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); 73} 74 75} // namespace android 76