Here you can find the source of truncateTimestamp(Timestamp timestamp, String period)
Parameter | Description |
---|---|
Timestamp | timestamp |
String | period |
public static Timestamp truncateTimestamp(Timestamp timestamp, String period)
//package com.java2s; /*//from w ww. jav a2s . com // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI licenses this file // to you 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.sql.Timestamp; import java.util.Calendar; public class Main { private static final String HOURLY = "HOURLY"; private static final String DAILY = "DAILY"; private static final String WEEKLY = "WEEKLY"; private static final String MONTHLY = "MONTHLY"; private static final String YEARLY = "YEARLY"; private static final String SECOND = "SECOND"; private static final String MINUTE = "MINUTE"; private static final String MONTH = "MONTH"; /** * Truncate the specified field of a java.sql.Timestamp * * @param Timestamp timestamp * @param String period * @return Timestamp */ public static Timestamp truncateTimestamp(Timestamp timestamp, String period) { Timestamp ts = null; if (period != null) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(timestamp.getTime()); if (period.equalsIgnoreCase(HOURLY)) { cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); } else if (period.equalsIgnoreCase(DAILY)) { cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); } else if (period.equalsIgnoreCase(WEEKLY)) { cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); } else if (period.equalsIgnoreCase(MONTHLY)) { cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.DAY_OF_MONTH, 1); } else if (period.equalsIgnoreCase(YEARLY)) { cal.set(Calendar.MILLISECOND, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.MONTH, Calendar.JANUARY); } ts = new Timestamp(cal.getTimeInMillis()); } return (ts != null) ? ts : timestamp; } }