Android Calendar to String Convert convertToDateStamp(Calendar cal)

Here you can find the source of convertToDateStamp(Calendar cal)

Description

Convert given date to string
OutputFormat: yyyymmdd_hhmm

Return

The Date/Time in the format: yyyymmdd_hhmm

Declaration

public static String convertToDateStamp(Calendar cal) 

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/*from   ww  w  .  j  a  v  a  2 s .  co 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. toSimpleDate(Calendar calendar)
  2. toHumanDate(Calendar cal)
  3. calendarToString(Calendar date)