-1

I have a string like this 210115 I want to represent it as 21:01:15 any ideas?. I tried using Gregorian calendar but it adds date to it which I don't want

SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");
Date date = new Date();
try{
 date = sdf.parse("210115");
}
 catch(Exception e){
}

Calendar calendar = GregorianCalendar.getInstance();
calendar.setTime(date);
System.out.print(calendar.getTime());

Output is Thu Jan 01 21:01:15 UTC 1970 but what I want is just 21:01:15

Thanks.

Ayo K
  • 1,719
  • 2
  • 22
  • 34
  • 2
    There is no time without Date as a date object – Jens Apr 26 '17 at 11:36
  • The question is why even convert to date, if you simply want a string? Just do: String s = "210115"; String output = s.substring(0,2) + ":" + s.substring(2,2) + ":" + s.substring(4,2); – Nicolae Natea Apr 26 '17 at 11:43
  • Possible duplicate of [Change date format in a Java string](http://stackoverflow.com/questions/4772425/change-date-format-in-a-java-string) – Robin Topper Apr 26 '17 at 11:44
  • Use `java.time.LocalTime` instead of class `java.util.Date`. Class `Date` is not suitable for holding only a time without a date. – Jesper Apr 26 '17 at 12:06

3 Answers3

2

To output a formatted date, you use another SimpleDateFormat object with a pattern with the format you want.

In this case, it sounds like you might want to use something like

SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println( outputFormat.format(date) );

Prisoner
  • 49,922
  • 7
  • 53
  • 105
2

So what you want is just a time, without time zone. I would recommend using the LocalTime class, which is exactly that, instead of the Date class.

LocalTime time = LocalTime.parse("210115", DateTimeFormatter.ofPattern("HHmmss"));
assylias
  • 321,522
  • 82
  • 660
  • 783
0

If u r getting the date string in "210115" this format and you want it in "21:01:15" format then why are you using date format. Simply do string operation as:

  String time="210115";
        String newtime=time.substring(0,2)+":"+time.substring(2,4)+":"+time.substring(4,6);
        System.out.println(newtime);

you will get the required format.21:01:15

Amit Gujarathi
  • 1,090
  • 1
  • 12
  • 25