Java Unix Date getUnixDate(Date date)

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

Description

Get unix style date string.

License

Open Source License

Declaration

public static String getUnixDate(Date date) 

Method Source Code

//package com.java2s;
/***************************************************************************
 * Copyright (c) 2006 Eike Stepper, Fuggerstr. 39, 10777 Berlin, Germany.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * //  w w w  .  j a  v  a2  s .  c o m
 * Contributors:
 *    Eike Stepper - initial API and implementation
 **************************************************************************/

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    private static final String[] MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct",
            "Nov", "Dec" };
    private final static ThreadLocal AFTER_SIX = new ThreadLocal() {

        protected Object initialValue() {
            return new SimpleDateFormat(" yyyy");
        }
    };
    private final static ThreadLocal BEFORE_SIX = new ThreadLocal() {

        protected Object initialValue() {
            return new SimpleDateFormat("HH:mm");
        }
    };

    /**
     * Get unix style date string.
     */
    public static String getUnixDate(Date date) {
        long dateTime = date.getTime();
        if (dateTime < 0) {
            return "------------";
        }

        Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        String firstPart = MONTHS[cal.get(Calendar.MONTH)] + ' ';

        String dateStr = String.valueOf(cal.get(Calendar.DATE));
        if (dateStr.length() == 1) {
            dateStr = ' ' + dateStr;
        }
        firstPart += dateStr + ' ';

        long nowTime = System.currentTimeMillis();
        if (Math.abs(nowTime - dateTime) > 183L * 24L * 60L * 60L * 1000L) {
            DateFormat fmt = (DateFormat) AFTER_SIX.get();
            return firstPart + fmt.format(date);
        } else {
            DateFormat fmt = (DateFormat) BEFORE_SIX.get();
            return firstPart + fmt.format(date);
        }
    }
}

Related

  1. escapeUnixChar(String strToEscape)
  2. getDispTimeByUnixTime(long unixSec)
  3. getUnixDate()
  4. getUnixDate(long millis)
  5. getUnixDate(String s)
  6. getUnixTime(String dateTime)
  7. getUnixTime2NoneTime(String longTime)