Java tutorial
//package com.java2s; /* * Copyright (C) 2011,2012 Southern Storm Software, Pty Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.Calendar; public class Main { /** * Formats a date/time value as a string. * * @param date the date to format * @return the formatted date */ public static String formatDateTime(Calendar date) { StringBuilder builder = new StringBuilder(16); appendField(builder, date.get(Calendar.YEAR), 4); appendField(builder, date.get(Calendar.MONTH) + 1, 2); appendField(builder, date.get(Calendar.DAY_OF_MONTH), 2); appendField(builder, date.get(Calendar.HOUR_OF_DAY), 2); appendField(builder, date.get(Calendar.MINUTE), 2); appendField(builder, date.get(Calendar.SECOND), 2); return builder.toString(); } private static void appendField(StringBuilder builder, int value, int digits) { int divider = 1; while (digits-- > 1) divider *= 10; while (divider != 0) { builder.append((char) ('0' + (value / divider) % 10)); divider /= 10; } } }