Here you can find the source of timestampToString(Timestamp ts, Calendar cal)
Parameter | Description |
---|---|
ts | The timestamp to be formatted. |
cal | The Calendar |
public static String timestampToString(Timestamp ts, Calendar cal)
//package com.java2s; /********************************************************************** Copyright (c) 2004 Brendan de Beer and others. All rights reserved. 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/*from w ww. j a v a 2s . c om*/ 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. Contributors: 2004 Brendan de Beer - Initial contributor for conversion methods 2005 Erik Bengtson - refactor mapping 2005 Andy Jefferson - added Timestamp/String converters ... **********************************************************************/ import java.sql.Timestamp; import java.util.Calendar; public class Main { /** Used to zero-fill the fractional seconds to nine digits. */ private static final String ZEROES = "000000000"; /** * Formats a timestamp in JDBC timestamp escape format using the timezone * of the passed Calendar. * @param ts The timestamp to be formatted. * @param cal The Calendar * @return A String in <tt>yyyy-mm-dd hh:mm:ss.fffffffff</tt> format. * @see java.sql.Timestamp */ public static String timestampToString(Timestamp ts, Calendar cal) { cal.setTime(ts); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; // Months are zero based in Calendar int day = cal.get(Calendar.DATE); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); String yearString = Integer.toString(year); String monthString = month < 10 ? "0" + month : Integer.toString(month); String dayString = day < 10 ? "0" + day : Integer.toString(day); String hourString = hour < 10 ? "0" + hour : Integer.toString(hour); String minuteString = minute < 10 ? "0" + minute : Integer.toString(minute); String secondString = second < 10 ? "0" + second : Integer.toString(second); String nanosString = Integer.toString(ts.getNanos()); if (ts.getNanos() != 0) { // Add leading zeroes nanosString = ZEROES.substring(0, ZEROES.length() - nanosString.length()) + nanosString; // Truncate trailing zeroes int truncIndex = nanosString.length() - 1; while (nanosString.charAt(truncIndex) == '0') { --truncIndex; } nanosString = nanosString.substring(0, truncIndex + 1); } return (yearString + "-" + monthString + "-" + dayString + " " + hourString + ":" + minuteString + ":" + secondString + "." + nanosString); } }