Reputation: 1026
How to store date and time in different variable from this type of date in java
Aug 29 2011 2:24PM
i want store date = 8/29/2011 and time = 2:24PM
hows it possible?
Upvotes: 0
Views: 136
Reputation: 7737
Try This
String inputDateInString = "Aug 29 2011 2:24PM";
DateFormat formatter = new SimpleDateFormat("MMM dd yyyy h:mmaa");
try {
Date dateObject = formatter.parse(inputDateInString);
String date = new SimpleDateFormat("dd/MM/yyyy").format(dateObject);
String time = new SimpleDateFormat("h:mmaa").format(dateObject);
} catch (ParseException e) {
e.printStackTrace();
}
Upvotes: 4
Reputation: 1
If you want to get hold of the Year, Month, Week, Day etc, the Calendar class would be what you are looking for.
Calendar c = Calendar.getInstance();
System.out.println("Year: " + c.get(Calendar.YEAR));
System.out.println("Month: " + c.get(Calendar.MONTH));
....
Upvotes: 0
Reputation: 29199
Actually, your question is not very clear, but I assume you want to get day, month, etc fields from the date in String. So use SimpleDateFormat to achieve this.
String date="Aug 29 2011 2:24PM";
DateFormat format = new SimpleDateFormat("MMM dd yyyy HH:mm");
Date dt= format.parse(date);
Calendar calendar=Calendar.getInstance();
calendar.setDate(dt);
int d= calendar.get(Calendar.DAY_OF_MONTH);
Upvotes: 0
Reputation: 1712
Here is an example using the SimpleDateFormat class
Date today = new Date();
DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
DateFormat year = new SimpleDateFormat("yyyy");
DateFormat month = new SimpleDateFormat("MM");
DateFormat day = new SimpleDateFormat("dd");
System.out.println("today is: " + format.format(today));
System.out.println("The year is: " + year.format(today));
System.out.println("The month is: " + month.format(today));
System.out.println("The day is: " + day.format(today));
Upvotes: 0