Java tutorial
//package com.java2s; /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.TimeZone; import android.app.Activity; import android.text.format.DateFormat; import android.text.format.DateUtils; import android.text.format.Time; import android.widget.TextView; public class Main { public static void setTime(Activity activity, TextView view, Time tm, int hourOfDay, int minute) { setTime(activity, view, getTime(tm, hourOfDay, minute)); } public static void setTime(Activity activity, TextView view, long millis) { int flags = DateUtils.FORMAT_SHOW_TIME; flags |= DateUtils.FORMAT_CAP_NOON_MIDNIGHT; if (DateFormat.is24HourFormat(activity)) { flags |= DateUtils.FORMAT_24HOUR; } // Unfortunately, DateUtils doesn't support a timezone other than the // default timezone provided by the system, so we have this ugly hack // here to trick it into formatting our time correctly. In order to // prevent all sorts of craziness, we synchronize on the TimeZone class // to prevent other threads from reading an incorrect timezone from // calls to TimeZone#getDefault() // TODO fix this if/when DateUtils allows for passing in a timezone String timeString; synchronized (TimeZone.class) { timeString = DateUtils.formatDateTime(activity, millis, flags); TimeZone.setDefault(null); } view.setTag(millis); view.setText(timeString); } public static long getTime(Time tm, int hourOfDay, int minute) { // Cache the member variables locally to avoid inner class overhead. tm.hour = hourOfDay; tm.minute = minute; // Cache the millis so that we limit the number of calls to // normalize() and toMillis(), which are fairly expensive. long millis = tm.normalize(true); return millis; } }