Java String to Date toDateString(java.util.Date date)

Here you can find the source of toDateString(java.util.Date date)

Description

Makes a date String in the format MM/DD/YYYY from a Date

License

Open Source License

Parameter

Parameter Description
date The Date

Return

A date String in the format MM/DD/YYYY

Declaration

public static String toDateString(java.util.Date date) 

Method Source Code


//package com.java2s;

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main {
    /**/*from   w w  w .  j a va 2s  .c  o m*/
     * Makes a date String in the format MM/DD/YYYY from a Date
     *
     * @param date The Date
     * @return A date String in the format MM/DD/YYYY
     */
    public static String toDateString(java.util.Date date) {
        if (date == null)
            return "";
        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int year = calendar.get(Calendar.YEAR);
        String monthStr;
        String dayStr;
        String yearStr;

        if (month < 10) {
            monthStr = "0" + month;
        } else {
            monthStr = "" + month;
        }
        if (day < 10) {
            dayStr = "0" + day;
        } else {
            dayStr = "" + day;
        }
        yearStr = "" + year;
        return monthStr + "/" + dayStr + "/" + yearStr;
    }

    public static String toDateString(java.util.Date d, String pattern) {

        String rs = "";

        try {
            SimpleDateFormat formatter = new SimpleDateFormat(pattern);
            rs = formatter.format(d);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return isFirstStartDate(rs) ? "" : rs;

    }

    private static boolean isFirstStartDate(String strDate) {
        if (strDate.compareTo("1970-01-01") == 0 || strDate.compareTo("1899-12-30") == 0
                || strDate.compareTo("1969-12-31") == 0) {
            return true;
        }
        return false;
    }
}

Related

  1. toDateString(Date date, String format)
  2. toDateString(Date date, String formatPattern)
  3. toDateString(Date date, TimeZone timezone)
  4. toDateString(final Date date)
  5. toDateString(java.util.Date date)
  6. toDateString(java.util.Date date, String format)
  7. toDateString(java.util.Date date, String spe)
  8. toDateString(long lval)
  9. toDateString(long ms)