Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

how to split a date value?

  Asked By: Diem    Date: Mar 27    Category: Java    Views: 14511
  


I'm a fresh person to Java. how can i split a date value(dd-mm-yyyy) into
year,month,day parts. can any one help me for this with coding.

Share: 

 

3 Answers Found

 
Answer #1    Answered By: Midissia Lopez     Answered On: Mar 27

Well if the date  is just a string then just use
java.lang.String.split(). ie.

String dt = "01-23-2004";
String dateParts[] = dt.split("-");
String month  = dateParts[0];
String day  = dateParts[1];
String year = dateParts[2];

If you're using an actual "Date" class like java.util.Date or
java.sql.Date then you can use the java.util.Calendar class to get the
pieces of the date. ie.

Date dt;
.
.
.
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DATE);
int year = cal.get(Calendar.YEAR);

 
Answer #2    Answered By: Sebastien Anderson     Answered On: Mar 27

refer java.util.Calendar API (Java docs)

 
Answer #3    Answered By: Hu Chalthoum     Answered On: Mar 27

SimpleDateFormat dateFormatter = new SimpleDateFormat(
"MM/dd/yyyy");
ParsePosition parsePosition = new ParsePosition(0);
Calendar cal = Calendar.getInstance();
cal.setTime(dateFormatter.parse("03/03/2004",new
ParsePosition(0)));

This way you will get a refernce to calendar object.
Now you can get the values from the ref by using

int month  = cal.get(Calendar.MONTH) + 1;
int day  = cal.get(Calendar.DATE);
int year = cal.get(Calendar.YEAR);

 
Didn't find what you were looking for? Find more on how to split a date value? Or get search suggestion and latest updates.




Tagged: