Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert millisecond String to Date in Java

Tags:

java

string

date

i have a String x = "1086073200000" . This is basically millisecond which I need to convert to a Date.

To convert i am using

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

long tempo1=Long.parseLong(x);
System.out.println(tempo1);  // output is 86073200000 instead of the whole thing
long milliSeconds=1346482800000L;

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
System.out.println(formatter.format(calendar.getTime())); 

The problem is when i convert the string x to long , some digits go away due to the limit on the size of long.

How do I preserve the entire String.

THanks.

like image 413
jseth Avatar asked Sep 20 '12 00:09

jseth


People also ask

How do you convert milliseconds to dates?

This is the number of seconds since the 1970 epoch. To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

Does Java Util date have milliseconds?

The java. util. Date class represents a particular moment in time, with millisecond precision since the 1st of January 1970 00:00:00 GMT (the epoch time).


2 Answers

double tempo=Double.parseDouble(z);

Why are you parsing your String which is supposed to be a Long as a Double?

Try using Long.parseLong:

String x = "1086073200000"

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

long milliSeconds= Long.parseLong(x);
System.out.println(milliSeconds);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
System.out.println(formatter.format(calendar.getTime())); 
like image 176
Tim Bender Avatar answered Oct 03 '22 02:10

Tim Bender


I tried this code and it worked for me

public static void main(String[] args) {
    String x = "1086073200000";
    long foo = Long.parseLong(x);
    System.out.println(x + "\n" + foo);

    Date date = new Date(foo);
    DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
    System.out.println(formatter.format(date)); 
}
like image 27
enTropy Avatar answered Oct 03 '22 03:10

enTropy