I have the following string 02/11/2012 23:11
Is there any way to convert this to the long 021120122311l?
I am trying to map objects to a specific position in an array based on their date created.
14 Answers
you can use a SimpleDateFormat to generate it as a string without any symbol, and then parse the long value using the Long class
SimpleDateFormat s1 = new SimpleDateFormat("dd/MM/yyyy HH:mm"); SimpleDateFormat s2 = new SimpleDateFormat("ddMMyyyyHHmm"); Date d = s1.parse("02/11/2012 23:11"); String s3 = s2.format(d); System.out.println(s3); long l = Long.parseLong(s3); System.out.println(l); 3You can try this
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm"); Date inputDate; try { inputDate = simpleDateFormat.parse("02/11/2012 23:11"); System.out.println(inputDate.getTime()); } catch (ParseException e) { e.printStackTrace(); } ouput:
1351878060000 Try this,
String dateValue = "02/11/2012 23:11"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm"); Date date = simpleDateFormat.parse(dateValue); simpleDateFormat = new SimpleDateFormat("ddMMyyyyHHmm"); String value = simpleDateFormat.format(date); Long result = Long.parseLong(value); System.out.println("Result : "+result); Time zone is critical to parsing a string into a date-time value unless you absolutely sure all the strings represent date-times occurring in the same time zone.
Joda-Time makes this work much easier.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy hh:mm" ); DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" ); DateTime dateTime = formatter.withZone( timeZone ).parseDateTime( myString ); long millisecondsSinceEpoch = dateTime.getMillis();