0

Is there a way for me to convert a String in milliseconds to a Date object?

In my program, I have to convert a Date in MM/dd/yyyy format to milliseconds, but then I have to pass that to a Date object.

Below, dateStringFinal is a String with the format "MM/dd/yyyy" already.

Calendar dateInCal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    try {
        dateInCal.setTime(sdf.parse(dateStringFinal));
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
String dateInMilli = String.valueOf(dateInCal.getTimeInMillis());

Then I have to set a date variable

someBean.setBeginDate(dateInMilli);

But dateInMilli should be a Date object. Any ideas?

Nicole
  • 39
  • 1
  • 9

4 Answers4

6
new Date(Long.valueOf(dateInMs));

However, SimpleDateFormat.parse() already returns a Date.

stealthjong
  • 10,858
  • 13
  • 45
  • 84
Mirko Adari
  • 5,083
  • 1
  • 15
  • 23
0

How about using Long.parseLong(String):

someBean.setBeginDate(Long.parseLong(dateInMilli));
PermGenError
  • 45,977
  • 8
  • 87
  • 106
0

You can get Date immediately from calendar with calendar.getTime().

partlov
  • 13,789
  • 6
  • 63
  • 82
0

dateInCal.getTimeInMillis() returns Long. keep it in Long instead of String. And then use Date constructor that takes Long:

Long dateInMilli = dateInCal.getTimeInMillis();
someBean.setBeginDate(new Date(dateInMilli));
Michael Gantman
  • 7,315
  • 2
  • 19
  • 36