-1

I have a string e.g. Thu May 10 15:48:23 IST 2018. How to convert this string in the form of Calendar object with format 2018-05-10 15:48:23.84.

ABHISHEK KUMAR
  • 71
  • 1
  • 10
  • 2
    You use a `DateTimeFormatter` to parse the `String` to a `LocalDateTime` object and then you use another `DateTimeFormatter` to format that value into another `String` – MadProgrammer May 11 '18 at 07:06
  • @MadProgrammer Thank you for your response. I actually want the end result as Calendar Object with required format, not a string. – ABHISHEK KUMAR May 11 '18 at 07:10
  • @ABHISHEKSRIVASTAVA 1. `Calendar` is out of date, you shouldn't be using it anymore; 2. `Calendar` (and `Date` and all other "date/time" class) are just containers of a value representing some point in time, they do not have any kind of "formatting" capabilities of their own – MadProgrammer May 11 '18 at 07:12
  • Agree that you should avoid `Calendar` completely and use `java.time`. That said, a `Calendar` cannot have a format in it. Any format you want to have, you can have it only in a `String`. This is also a sound separation between your model/business data and the presentation of the data to a user. – Ole V.V. May 11 '18 at 10:56

1 Answers1

1

Start by using having a look at DateTimeFormatter and Parsing and Formatting for more details about how to parse and format date/time values in Java 8+

Based on your examples, something like...

String inValue = "Thu May 10 15:48:23 IST 2018";
DateTimeFormatter inFormatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(inValue, inFormatter);
DateTimeFormatter outFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS", Locale.ENGLISH);
String outValue = outFormatter.format(ldt);
System.out.println(outValue);

Will print 2018-05-10 15:48:23.00

Thank you for your response. I actually want the end result as Calendar Object with required format, not a string.

  1. Calendar is effectively deprecated, you shouldn't be using it anymore. Even if you're not using Java 8+, you should be using the ThreeTen Backport API
  2. Calendar (and Date and all other "date/time" class) are just containers of a value representing some point in time, they do not have any kind of "formatting" capabilities of their own. This is why the API has formatting classes. Keep you date/time values represented as appropriate classes until you need to display them, at that point, you should format the value to a String
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366