Java tutorial
//package com.java2s; /******************************************************************************* * Copyright (c) 2011 Adam Shanks (ChainsDD) * * 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 android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.text.format.DateFormat; public class Main { public static String formatDateTime(Context context, long date) { return formatDate(context, date) + " " + formatTime(context, date); } public static String formatDate(Context context, long date) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String format = prefs.getString("pref_date_format", "default"); if (format.equals("default")) { return DateFormat.getDateFormat(context).format(date); } else { return (String) DateFormat.format(format, date); } } public static String formatTime(Context context, long time) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean hour24 = prefs.getBoolean("pref_24_hour_format", true); boolean showSeconds = prefs.getBoolean("pref_show_seconds", false); String hour = "kk"; String min = "mm"; String sec = ":ss"; String post = ""; if (hour24) { hour = "kk"; } else { hour = "hh"; post = "aa"; } if (showSeconds) { sec = ":ss"; } else { sec = ""; } String format = String.format("%s:%s%s%s", hour, min, sec, post); return (String) DateFormat.format(format, time); } }