1 /* 2 * Copyright (C) 2014 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 package com.android.bluetooth.mapclient; 18 19 import java.util.Calendar; 20 import java.util.Date; 21 import java.util.Locale; 22 import java.util.TimeZone; 23 import java.util.regex.Matcher; 24 import java.util.regex.Pattern; 25 26 public final class ObexTime { 27 28 private Date mDate; 29 ObexTime(String time)30 public ObexTime(String time) { 31 /* 32 * match OBEX time string: YYYYMMDDTHHMMSS with optional UTF offset 33 * +/-hhmm 34 */ 35 Pattern p = Pattern 36 .compile( 37 "(\\d{4})(\\d{2})(\\d{2})T(\\d{2})(\\d{2})(\\d{2})(([+-])(\\d{2})(\\d{2})" 38 + ")?"); 39 Matcher m = p.matcher(time); 40 41 if (m.matches()) { 42 43 /* 44 * matched groups are numberes as follows: YYYY MM DD T HH MM SS + 45 * hh mm ^^^^ ^^ ^^ ^^ ^^ ^^ ^ ^^ ^^ 1 2 3 4 5 6 8 9 10 all groups 46 * are guaranteed to be numeric so conversion will always succeed 47 * (except group 8 which is either + or -) 48 */ 49 50 Calendar cal = Calendar.getInstance(); 51 cal.set(Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2)) - 1, 52 Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)), 53 Integer.parseInt(m.group(5)), Integer.parseInt(m.group(6))); 54 55 /* 56 * if 7th group is matched then we have UTC offset information 57 * included 58 */ 59 if (m.group(7) != null) { 60 int ohh = Integer.parseInt(m.group(9)); 61 int omm = Integer.parseInt(m.group(10)); 62 63 /* time zone offset is specified in miliseconds */ 64 int offset = (ohh * 60 + omm) * 60 * 1000; 65 66 if (m.group(8).equals("-")) { 67 offset = -offset; 68 } 69 70 TimeZone tz = TimeZone.getTimeZone("UTC"); 71 tz.setRawOffset(offset); 72 73 cal.setTimeZone(tz); 74 } 75 76 mDate = cal.getTime(); 77 } 78 } 79 ObexTime(Date date)80 public ObexTime(Date date) { 81 mDate = date; 82 } 83 getTime()84 public Date getTime() { 85 return mDate; 86 } 87 88 @Override toString()89 public String toString() { 90 if (mDate == null) { 91 return null; 92 } 93 94 Calendar cal = Calendar.getInstance(); 95 cal.setTime(mDate); 96 97 /* note that months are numbered stating from 0 */ 98 return String.format(Locale.US, "%04d%02d%02dT%02d%02d%02d", 99 cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, 100 cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY), 101 cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)); 102 } 103 } 104