user1197252
user1197252

Reputation:

Separate Date and Time objects

I have a web-form where users can select a date from a calendar pop-up and a time from a dropdown. At the moment I am trying to store the date using a Date object.

@Required
public Date date;

And the output of this object is something like:

January 1, 1970, 00:00:00 GMT

What I would really like to do is separate this and store the date in a format like 27/02/2013 and have the time as a separate object in 24 hour format e.g. 23:45. I am unsure how to do this with java.

Resolved using SimpleDateFormat:

//also the import
import java.text.*;

@Required
public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
public String date = simpleDateFormat.format(new Date());

@Required
public SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("hh:mm");
public String time = simpleTimeFormat.format(new Date());

Upvotes: 4

Views: 9002

Answers (2)

Gabriel Câmara
Gabriel Câmara

Reputation: 1249

Try this:

SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");

String dateAsString = dateFormatter.format(date);
String timeAsString = timeFormatter.format(date);

Upvotes: 2

user
user

Reputation: 3088

Have a look at the Calendar class. It has all of the methods required to get different "date parts". Also, look at the SimpleDateFormat class in java to format the date in needed way.

Calendar - http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

SimpleDateFormat - http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Upvotes: 5

Related Questions