0

I have a python date formatted like this 1418572798.498 within a string. In Java the dates are formatted like this 1418572798498.

How to convert this string to Java date? Is there any third party library to use for the conversion?

Roman C
  • 49,761
  • 33
  • 66
  • 176
dwzhao
  • 87
  • 1
  • 9
  • 1
    That's not "python time", btw. That's Unix/POSIX time (seconds since 1970-01-01 00:00:00). "Java time" is the same but in microseconds :-P – Ricardo Cárdenes Jan 02 '15 at 16:33
  • You just turn the string into a float, and then multiply that number by 1000 – Anthony Pham Jan 02 '15 at 16:33
  • 1
    @RicardoCárdenes No, not microseconds. The java.util.Date class uses milliseconds since epoch, as does the Joda-Time library. The new java.time package in Java 8 (JSR 310) uses nanoseconds since epoch. Some databases such as Postgres use microseconds since epoch. See [this diagram](http://i.stack.imgur.com/cpOL8.png). – Basil Bourque Jan 02 '15 at 16:46
  • Sorry, miliseconds. That was a brainfart. – Ricardo Cárdenes Jan 02 '15 at 16:47
  • @davidzhao Please search StackOveflow before posting. This question has been addressed *many* times. – Basil Bourque Jan 02 '15 at 16:48
  • @BasilBourque, i konw that question, but they are different. i just want to konw is there any better ways. thans for your wanning. – dwzhao Jan 02 '15 at 16:54
  • @davidzhao You should explain in your Question how it is different from near duplicates. I don't see a difference yet. Same answer for your Question and the many duplicates: Convert string to a number, multiply by a thousand to get a long/Long, feed to constructor of java.util.Date (or better, Joda-Time). – Basil Bourque Jan 02 '15 at 16:58

3 Answers3

5

Try something like:

String number = "1418572798.498";
long d = Long.parseLong(number.replace(".", ""));
System.out.println(d + " " + new Date(d));
Output:
1418572798498 Sun Dec 14 21:29:58 IST 2014
SMA
  • 36,381
  • 8
  • 49
  • 73
2

Do this:

float time = Float.parseFloat(string);
long actual_time = (int)(time*1000);
Date d = new Date(actual_time);
SalmonKiller
  • 2,183
  • 4
  • 27
  • 56
1

Remove the decimal point and convert it to a float.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101