com.sqewd.os.maracache.api.utils.TimeUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.sqewd.os.maracache.api.utils.TimeUtils.java

Source

/*
 * Copyright 2014, Subhabrata Ghosh
 *
 * 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.
 */

package com.sqewd.os.maracache.api.utils;

import org.joda.time.DateTime;

import java.util.concurrent.TimeUnit;

/**
 * Utility functions for time.
 *
 * @author Subho Ghosh (subho dot ghosh at outlook.com)
 * @created 26/05/14
 */
public class TimeUtils {

    /**
     * Get the time bucket for the input date based on the Time Unit and Unit multiplier specified.
     *
     * @param dt         - Date time to bucket.
     * @param unit       - Time Unit
     * @param multiplier - Unit multiplier.
     * @return
     */
    public static DateTime bucket(DateTime dt, TimeUnit unit, int multiplier) {
        DateTime w = null;
        switch (unit) {
        case MILLISECONDS:
            int ms = (dt.getMillisOfSecond() / multiplier) * multiplier;
            w = dt.secondOfMinute().roundFloorCopy().plusMillis(ms);
            break;
        case SECONDS:
            int s = (dt.getSecondOfMinute() / multiplier) * multiplier;
            w = dt.minuteOfHour().roundFloorCopy().plusSeconds(s);
            break;
        case MINUTES:
            int m = (dt.getMinuteOfHour() / multiplier) * multiplier;
            w = dt.hourOfDay().roundFloorCopy().plusMinutes(m);
            break;
        case HOURS:
            int h = (dt.getHourOfDay() / multiplier) * multiplier;
            w = dt.dayOfYear().roundFloorCopy().plusHours(h);
            break;
        case DAYS:
            int d = (dt.getDayOfYear() / multiplier) * multiplier;
            // Need to subtract (1) as the start offset i
            if (dt.getDayOfYear() % multiplier == 0) {
                d -= 1;
            }
            w = dt.yearOfCentury().roundFloorCopy().plusDays(d);
            break;
        }
        return w;
    }
}