Budi Darmawan
Budi Darmawan

Reputation: 3813

get current date and time

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!

Upvotes: 7

Views: 26875

Answers (7)

Sanjay Kumaar
Sanjay Kumaar

Reputation: 48

This works,

 String currentDateTime;

 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 currentDateTime = sdf1.format(new Date());

Upvotes: 0

Passionate Androiden
Passionate Androiden

Reputation: 732

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());

Upvotes: 0

Mihir Patel
Mihir Patel

Reputation: 412

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()

Upvotes: -1

duffymo
duffymo

Reputation: 308743

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);

Upvotes: 9

Rahul
Rahul

Reputation: 10625

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

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
     currentDateandTime = sdf.format(new Date());

Upvotes: 0

jamis0n
jamis0n

Reputation: 3800

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());

Upvotes: -1

Adam Keenan
Adam Keenan

Reputation: 784

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);

Upvotes: 3

Related Questions