Java Duration roundedRelativeFormat()

Here you can find the source of roundedRelativeFormat()

Description

rounded Relative Format

License

Open Source License

Declaration

public static DateFormat roundedRelativeFormat() 

Method Source Code

//package com.java2s;
/*//from w w w . java 2 s. c  o  m
 * Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  The ASF 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.  For additional information regarding
 * copyright in this work, please see the NOTICE file in the top level
 * directory of this distribution.
 */

import java.text.ParsePosition;
import java.text.DateFormat;
import java.text.FieldPosition;

import java.util.Date;

public class Main {
    public static DateFormat roundedRelativeFormat() {
        return new DateFormat() {

            public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
                // TODO: Some better (and more localizable) way to do this?
                Date now = new Date();
                long secondsDiff = (now.getTime() - date.getTime()) / 1000;
                if (secondsDiff <= 1) {
                    return toAppendTo.append("1 second ago");
                } else if (secondsDiff < 60) {
                    return toAppendTo.append(secondsDiff).append(" seconds ago");
                } else if (secondsDiff < (2 * 60)) {
                    return toAppendTo.append("1 minute ago");
                } else if (secondsDiff < (60 * 60)) {
                    return toAppendTo.append((secondsDiff / 60)).append(" minutes ago");
                } else if (secondsDiff < (2 * 60 * 60)) {
                    return toAppendTo.append("1 hour ago");
                } else if (secondsDiff < (24 * 60 * 60)) {
                    return toAppendTo.append((secondsDiff / (60 * 60))).append(" hours ago");
                } else if (secondsDiff < (2 * 24 * 60 * 60)) {
                    return toAppendTo.append("yesterday");
                } else {
                    return toAppendTo.append((secondsDiff / (24 * 60 * 60))).append(" days ago");
                }
            }

            public Date parse(String source, ParsePosition pos) {
                throw new UnsupportedOperationException();
            }
        };
    }
}

Related

  1. printDuration(double uptime)