Blog Archive

Android get current Date and Time cheat sheet

//Date format MM/DD/YYYY
private String getTodaysDate() {

    final Calendar c = Calendar.getInstance();

    return(new StringBuilder()
            .append(c.get(Calendar.MONTH) + 1).append("/")
            .append(c.get(Calendar.DAY_OF_MONTH)).append("/")
            .append(c.get(Calendar.YEAR)).append(" ")).toString();
}

//Time format HH:MM:SS
private String getCurrentTime() {

    final Calendar c = Calendar.getInstance();

    return(new StringBuilder()
            .append(c.get(Calendar.HOUR_OF_DAY)).append(":")
            .append(c.get(Calendar.MINUTE)).append(":")
            .append(c.get(Calendar.SECOND)).append(" ")).toString();
}

//Date format YYYYMMDD 
private String getTodaysDate2() { 

    final Calendar c = Calendar.getInstance();
    int todaysDate =     (c.get(Calendar.YEAR) * 10000) + 
    ((c.get(Calendar.MONTH) + 1) * 100) + 
    (c.get(Calendar.DAY_OF_MONTH));
    Log.w("DATE:",String.valueOf(todaysDate));
    return(String.valueOf(todaysDate));

}

//Time format HHMMSS
private String getCurrentTime2() {

    final Calendar c = Calendar.getInstance();
    int currentTime =     (c.get(Calendar.HOUR_OF_DAY) * 10000) + 
    (c.get(Calendar.MINUTE) * 100) + 
    (c.get(Calendar.SECOND));
    Log.w("TIME:",String.valueOf(currentTime));
    return(String.valueOf(currentTime));

}

Also you can use android.text.format.DateFormat

DateFormat.format("MM/dd/yy h:mmaa", System.currentTimeMillis()

This class takes as inputs a format string and a representation of a date/time. The format string controls how the output is generated. Formatting characters may be repeated in order to get more detailed representations of that field. For instance, the format character 'M' is used to represent the month. Depending on how many times that character is repeated you get a different representation.

For the month of September:
M -> 9
MM -> 09
MMM -> Sep
MMMM -> September

The effects of the duplication vary depending on the nature of the field. See the notes on the individual field formatters for details. For purely numeric fields such as HOUR adding more copies of the designator will zero-pad the value to that number of characters.

For 7 minutes past the hour:
m -> 7
mm -> 07
mmm -> 007
mmmm -> 0007

Examples for April 6, 1970 at 3:23am:
"MM/dd/yy h:mmaa" -> "04/06/70 3:23am"
"MMM dd, yyyy h:mmaa" -> "Apr 6, 1970 3:23am"
"MMMM dd, yyyy h:mmaa" -> "April 6, 1970 3:23am"
"E, MMMM dd, yyyy h:mmaa" -> "Mon, April 6, 1970 3:23am&
"EEEE, MMMM dd, yyyy h:mmaa" -> "Monday, April 6, 1970 3:23am"
"'Noteworthy day: 'M/d/yy" -> "Noteworthy day: 4/6/70"