Andrei Vasilev
Andrei Vasilev

Reputation: 607

How to convert a numeric value to date in Java?

I have a list of values 12012, 112013 , 52005 stored as strings and i need to convert them into Jan 2012, Nov 2013, May 2005 correspondingly. I know how I can do this using parsing the string and using the if statement. Is there any efficient way?

Upvotes: 0

Views: 5517

Answers (3)

Frederic Close
Frederic Close

Reputation: 9639

As you have strings representing dates that have two different formats Myyyy and MMyyyy, with a SimpleDateFormat I'm not sure you can avoid an if statement, that's how I would do it:

    SimpleDateFormat sdf1 = new SimpleDateFormat("Myyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("MMyyyy");
    Date d = null;
    if(5 == s.length()){
        d = sdf1.parse(s);
    }else if(6 == s.length()){
        d = sdf2.parse(s);
    }

Upvotes: 3

Lee Meador
Lee Meador

Reputation: 12985

Something like this might work:

String val = "12012";
int numVal = Integer.parseInt(val);
int year = numVal % 10000;
int month = numVal / 10000;
... create a date from that ...

I don't know whether you want a java Date or Calendar or whatever.

Calendar cal = Calendar.getInstance().clear();
cal.set(year, month-1, 1);

Date date = cal.getTime();

Or Joda Time for a date without a timezone:

LocalDate dt = new LocalDate(year, month, 1);

Upvotes: 4

Masudul
Masudul

Reputation: 21971

Using SimpleDateFormat pattern you can easily do that: Try following simple code:

String str="12012";//112013 , 52005
SimpleDateFormat format=new SimpleDateFormat("Myyyy");
SimpleDateFormat resFormat=new SimpleDateFormat("MMM yyyy");
Date date=format.parse(str);
System.out.println(resFormat.format(date));

Upvotes: 3

Related Questions