0

I have a little problem with the translation of this data 19/12/2005 17:30:45 to mileseconds. I don't know why, I am getting a wrong translation to Jun 28 17:30:45 CEST 1995 Time :804353445798

The code I used is this :

private static long ConvertTimeToTimeStamp(String time) {   

  Integer[] data = new Integer[6];
  String [] tokens = time.split(" "); 

  System.out.println(tokens[0]);
  System.out.println(tokens[1]);

  String[] d_m_y = tokens[0].split("/"); 
  String[] hh_mm_ss = tokens[1].split(":"); 

  for (int i = 0; i < d_m_y.length; i++) {
    data[i]=Integer.parseInt(d_m_y[i]); 
    // System.out.println(d_m_y[i]);        
  }

  for (int i = 0; i < hh_mm_ss.length; i++) {
    data[i+3]=Integer.parseInt(hh_mm_ss[i]); 
    //  System.out.println(hh_mm_ss[i]);    
  }
  //Calendar calendar =  Calendar.getInstance(); 
  GregorianCalendar calendar = new GregorianCalendar(); 
  calendar.set(data[0]+1970, data[1], data[2], data[3],data[4],data[5]);

  System.out.println(calendar.getTime().toString()); 
  return calendar.getTimeInMillis(); 
}

5 Answers 5

6

You should not parse the date manually - use a date format instead:

String s = "19/12/2005 17:30:45";
Date d = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(s);
Sign up to request clarification or add additional context in comments.

Comments

2

Treat this object from the outset as a date. That will be much more reliable.

Use SimpleDateFormat.parse() to parse your string into a date/time. Otherwise you're reduced to string parsing/splitting/recombining etc with no bounds-checking, type-checking etc. Your solution is stringly-typed, not strongly-typed.

I've referenced the standard Java libraries, but Joda-Time is a better bet for doing date work in Java and I would advise adopting this for a more intuitive and safer API.

1 Comment

'stringly-typed'? You sir, get a cookie!
1

Forget about it. Use a SimpleDataFormat object with pattern dd/MM/yyyy HH:mm:ss to parse() the String into a date object.

Comments

1

try...

private static long ConvertTimeToTimeStamp(String time) { 
   //19/12/2005 17:30:45
   SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
   java.util.Date d = sdf.parse(time);
   return d.getTime();
}

Comments

0

You are mixing the order of year, month and day. The set method is expecting them in the following order: year, month, day and you are providing them as day + 1970, month, year. Having said that, you might actually be much more happy with a library like joda-time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.