Blog Archive

Java get current Date and Time Example

package com.as400samplecode;

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

public class CurrentDateTime {

 public static void main(String[] args) {
 
  Date date = new Date(System.currentTimeMillis());
    
  //both Date and Time
  DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
  System.out.println(df.format(date));
    
  //just Date
  DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
  System.out.println(df1.format(date));
    
  //just Time
  DateFormat df2 = new SimpleDateFormat("HHmmss");
  System.out.println(df2.format(date));
   
   
 }
 
 private String getTodaysDate() {

        DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String todaysDate = dateFormat.format(System.currentTimeMillis());
        return todaysDate;

    }

    private String getCurrentTime() {

        DateFormat dateFormat = new SimpleDateFormat("kkmmss");
        String currentTime = dateFormat.format(System.currentTimeMillis());
        return currentTime;

    }


}

Java date and time formats

Letter     Date or Time Component     
G          Era designator          
y          Year     
M          Month in year     
w          Week in year     
W          Week in month     
D          Day in year     
d          Day in month     
F          Day of week in month     
E          Day in week     
a          Am/pm marker     
H          Hour in day (0-23)     
k          Hour in day (1-24)     
K          Hour in am/pm (0-11)     
h          Hour in am/pm (1-12)  
m          Minute in hour     
s          Second in minute     
S          Millisecond