Android Date to String Convert convertToDateStamp(Date date)

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

Description

Convert given date to string
OutputFormat: yyyymmdd_hhmm

Return

The Date/Time in the format: yyyymmdd_hhmm

Declaration

public static String convertToDateStamp(Date date) 

Method Source Code

//package com.java2s;

import java.util.Calendar;
import java.util.Date;

public class Main {
    /** Convert given date to string<br>
     *  OutputFormat: yyyymmdd_hhmm/*w  ww .  j  a  v  a  2 s.c  o m*/
     *  @return The Date/Time in the format: yyyymmdd_hhmm
     */
    public static String convertToDateStamp(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date(time));
        return convertToDateStamp(cal);
    }

    /** Convert given date to string<br>
     *  OutputFormat: yyyymmdd_hhmm
     *  @return The Date/Time in the format: yyyymmdd_hhmm
     */
    public static String convertToDateStamp(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return convertToDateStamp(cal);
    }

    /** Convert given date to string<br>
     *  OutputFormat: yyyymmdd_hhmm
     *  @return The Date/Time in the format: yyyymmdd_hhmm
     */
    public static String convertToDateStamp(Calendar cal) {
        String year = String.valueOf(cal.get(Calendar.YEAR));
        String month = String.valueOf(cal.get(Calendar.MONTH) + 1);
        if (month.length() == 1) {
            month = "0" + month;
        }
        String day = String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
        if (day.length() == 1) {
            day = "0" + day;
        }
        String hour = String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
        if (hour.length() == 1) {
            hour = "0" + hour;
        }
        String minute = String.valueOf(cal.get(Calendar.MINUTE));
        if (minute.length() == 1) {
            minute = "0" + minute;
        }
        String second = String.valueOf(cal.get(Calendar.SECOND));
        if (second.length() == 1) {
            second = "0" + second;
        }
        String dateStamp = year + month + day + "_" + hour + minute
                + second;
        return dateStamp;
    }
}

Related

  1. dateTimeToString(Date date)
  2. dateToIsoDateString(@NotNull Date date)
  3. dateToIsoDateString(@Nullable Date date, @NotNull DateFallback fallback)
  4. formatDate(Date date, String format)