6

I'm kind of stuck on date and time. I want my program to create the date like this "20121217". The first 4 letters are the year, the second 2 letters are the month and the last 2 are the day. year+month+day

The time is "112233" hour+minute+second

Thanks for your help!

Budi Darmawan
  • 3,743
  • 3
  • 14
  • 7

7 Answers7

9

That's a formatting issue. Java uses java.util.Date and java.text.DateFormat and java.text.SimpleDateFormat for those things.

DateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd hhmmss");
dateFormatter.setLenient(false);
Date today = new Date();
String s = dateFormatter.format(today);
duffymo
  • 305,152
  • 44
  • 369
  • 561
3

You can do something like this:

Calendar c = Calendar.getInstance();
String date = c.get(Calendar.YEAR) + c.get(Calendar.MONTH) + c.get(Calendar.DATE);
String time = c.get(Calendar.HOUR) + c.get(Calendar.MINUTE) + c.get(Calendar.SECOND);
Adam Keenan
  • 764
  • 1
  • 11
  • 29
0

Change any specific format of time or date as you need.

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
     currentDateandTime = sdf.format(new Date());
Rahul
  • 10,457
  • 4
  • 35
  • 55
0

For date:

DateFormat df = new SimpleDateFormat("yyyyMMdd");
String strDate = df.format(new Date());

For time:

DateFormat df = new SimpleDateFormat("hhmmss");
String strTime = df.format(new Date());
Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
0

This works,

 String currentDateTime;

 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 currentDateTime = sdf1.format(new Date());
Sanjay Kumaar
  • 690
  • 7
  • 17
-1

What you're looking for is the SimpleDateFormat in Java... Take a look at this page.

Try this for your need:

SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd hhmmss");
Date parsed = format.parse(new Date());
System.out.println(parsed.toString());
jamis0n
  • 3,610
  • 8
  • 34
  • 50
-1

You can use following method to get current time

 /**************************************************************
 * getCurrentTime() it will return system time
 * 
 * @return
 ****************************************************************/
public static String getCurrentTime() {     
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd HHmmss");
    Calendar cal = Calendar.getInstance();
    return dateFormat.format(cal.getTime());
}// end of getCurrentTime()
Mihir Patel
  • 404
  • 6
  • 14