Java Date to String dateToRelativeTime(Date date)

Here you can find the source of dateToRelativeTime(Date date)

Description

date To Relative Time

License

Apache License

Declaration

public static String dateToRelativeTime(Date date) 

Method Source Code

//package com.java2s;
/*/*from  w  w  w.  java2  s . co  m*/
 *
 *  Copyright 2014 http://Bither.net
 *
 *  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 java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static String dateToRelativeTime(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date now = new Date();
        long between = (now.getTime() - date.getTime()) / 1000;
        long day = between / (24 * 3600);
        long hour = between % (24 * 3600) / 3600;
        long minute = between % 3600 / 60;
        long second = between;

        String timeStr;
        if (day > 0 && day <= 29) {
            timeStr = day + " day " + hour + ":" + minute;
        } else if (day > 29) {
            timeStr = df.format(date);
        } else {
            if (hour > 0) {
                timeStr = hour + " hour " + minute + " minutes";
            } else {
                if (minute > 0) {
                    timeStr = minute + " minutes";
                } else {
                    timeStr = second + " seconds";
                }
            }
        }
        return timeStr;
    }
}

Related

  1. DateToInteger(Date date)
  2. dateToIso(Date d)
  3. dateToIso8601String(Date date)
  4. dateToISODate(Date date)
  5. dateToOracleDateString(Date date)
  6. dateToRFC1123(Date date)
  7. dateToRFC3339(Date d)
  8. dateToStr(Date date)
  9. dateToStr(Date date)