0

I have some time value which is in String format (for example 12:45 AM and 7:00 PM). I wonder how should I convert it into the 24 hours format (for example 12:45 and 19:00).

Should the output be in long format?

spongebob
  • 8,370
  • 15
  • 50
  • 83
QWERTY
  • 2,303
  • 9
  • 44
  • 85
  • 4
    can you post what you have done so far. – Vishvesh Phadnis Nov 26 '14 at 13:13
  • Do you want the output to be a `long`? Or are you asking about the best format? – spongebob Nov 26 '14 at 13:15
  • Just as a reminder: `12:45 AM` is `00:45` rather than `12:45` – devnull69 Nov 26 '14 at 13:53
  • @Joiner Yeah, I need the output to be long format – QWERTY Nov 26 '14 at 14:47
  • 1
    Why have you edited the code from one of the answers into the question? You haven't added anything about why you've done that - so it looks like it's part of the real question, which is somewhat odd. – Jon Skeet Nov 26 '14 at 16:06
  • @Denise You seem to be confusing the `long` [primitive data type](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html), [`Long`](https://docs.oracle.com/javase/8/docs/api/java/lang/Long.html?is-external=true) class, and [long format in a string representation](https://docs.oracle.com/javase/tutorial/i18n/format/dateFormat.html) of a date-time value. – Basil Bourque Nov 26 '14 at 17:11

3 Answers3

3

Please take a look at this page. It has examples how to convert it back and forth.

Here is the 12hrs to 24hrs conversion.

import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
import java.text.ParseException;

String input = "2014-12-20 10:22:12 PM";
//Format of the date defined in the input String
DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aa");
//Desired format: 24 hour format: Change the pattern as per the need
DateFormat outputformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
String output = null;
try{
   //Converting the input String to Date
   date= df.parse(input);
   //Changing the format of date and storing it in String
   output = outputformat.format(date);
   //Displaying the date
   System.out.println(output);
} catch (ParseException pe) {
   pe.printStackTrace();
}
spongebob
  • 8,370
  • 15
  • 50
  • 83
Dropout
  • 13,653
  • 10
  • 56
  • 109
  • 2
    That's a very unconventional date pattern - I'd recommend using yyyy-MM-dd instead. (Very few countries put the month first, and those that do don't typically use - as the separator.) – Jon Skeet Nov 26 '14 at 13:17
  • That's completely true @Jon, of course any further fiddling around with the format are possible. Thanks for the comment. – Dropout Nov 26 '14 at 13:18
  • 1
    Of course developers *can* fiddle with it themselves - I'm recommending editing your post to use a more standard format as a *default*, given that users are very likely to copy and paste with little thought :( – Jon Skeet Nov 26 '14 at 13:19
  • Do you have any ideas so that the output should be in long format? – QWERTY Nov 26 '14 at 14:15
  • What exactly do you mean @Denise ? – Dropout Nov 26 '14 at 14:24
  • Because your output is currently in String format. I need it to be in long so that I could use the .setWhen() for my android push-notification – QWERTY Nov 26 '14 at 14:29
  • How do you want a format like "12:45" to be Long? You can't use colons in Long. – Dropout Nov 26 '14 at 14:37
  • But is it possible to convert the time in string format to long? – QWERTY Nov 26 '14 at 14:44
  • Yes, if it can be converted. You can't convert a String that includes characters that aren't usable in Long format, like **:**. If you do `Long.parseLong("1234", 10)` you will end up with `1234L`, however if you do `Long.parseLong("12:34", 10)` it will produce a NumberFormatException.. Please check out http://stackoverflow.com/questions/7693324/how-to-convert-string-to-long-in-java – Dropout Nov 26 '14 at 14:51
  • I see. So for my case, can I assumed that it's not possible to do it? – QWERTY Nov 26 '14 at 14:57
  • Check this out http://stackoverflow.com/questions/12473550/how-to-convert-string-date-to-long-millseconds – Dropout Nov 26 '14 at 15:02
  • @Dropout But that example was convert from Date whereas my one was convert from String time :( – QWERTY Nov 26 '14 at 15:23
  • `date` variable is a Date object. Don't do `output = outputformat.format(date);` but instead convert the `date` to long as shown in the page I have mentioned above. – Dropout Nov 26 '14 at 15:25
  • Is this a task from school or something? I've seen this question asked about 5 times in the last hour :D – Dropout Nov 26 '14 at 15:26
  • Nah, it's my project. So basically I just do like my edited portion? – QWERTY Nov 26 '14 at 15:30
  • Yes, milliseconds can be converted without problems. – Dropout Nov 26 '14 at 15:32
  • Nope, with this I am getting parseError, Unparsable date: 12:30 AM at offset 2. Any ideas? Sorry because I keep on prompting questions :) – QWERTY Nov 26 '14 at 15:40
  • @Denise: If your value is *just* "12:30 AM" then it doesn't match the format of "yyyy-MM-dd hh:mm:ss aa"... you'd need to adjust that. – Jon Skeet Nov 26 '14 at 16:05
  • 1
    Dont think I was saying this just because my answer was first accepted and then unaccepted. Converting to long was not the part of your original question. If you edit it unaccepting the previous one was not good. Just saying – Murtaza Khursheed Hussain Nov 26 '14 at 16:45
  • 1
    Thank you @JonSkeet & Murtaza. Denise it would probably be most beneficial to the community if you posted the next part of the problem as a separate question so people could find it without going through the comments of this answer. – Dropout Nov 26 '14 at 16:51
2
String dateStr = "12:45 AM";
DateFormat inputFormat = new SimpleDateFormat( "hh:mm aa" );
DateFormat outputFormat = new SimpleDateFormat( "HH:mm" );
Date date = null;
try{
    date = inputFormat.parse( dateStr );
}
catch ( ParseException e ){
   e.printStackTrace();
}
if( date != null ){
    String formattedDate = outputFormat.format( date );
}
Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
  • 2
    I would suggest you remove the `aa` from your `writeFormat`... it's odd to see "19:00 PM" for example. (I'd also recommend removing the exception handling - that's almost never the right approach.) – Jon Skeet Nov 26 '14 at 13:15
  • Exactly, thanks. For Exception handling, its my signature + its good to have some exception handling. :) – Murtaza Khursheed Hussain Nov 26 '14 at 13:16
  • 1
    But that's not really exception handling - it's pretty much just ignoring it. Much better would be to show a method that declares that it might throw `ParseException`. Printing the stack trace and continuing is almost never the right approach, IMO - particularly as this should quite possibly be refactored into a reusable method anyway, where *sometimes* you want to ignore the exception and sometimes you don't... – Jon Skeet Nov 26 '14 at 13:20
  • Agree. I just showed the way. Obviously he should handle that exception if it comes to that point, i think that's why we have exceptions. – Murtaza Khursheed Hussain Nov 26 '14 at 13:21
  • 1
    "I just showed the way" - you showed *a* way, which is almost *never* appropriate. That's why I'm suggesting it should be changed. (Heck, even just using a logger rather than calling `e.printStackTrace()` would be *slightly* better, though not by much...) I curse the fact that Eclipse and other IDEs will generate this sort of try/catch block too easily - it makes developers lazy about thinking what they *really* want to do with exceptions. – Jon Skeet Nov 26 '14 at 13:24
  • But I need the output to be long. Any ideas? – QWERTY Nov 26 '14 at 13:30
  • @JonSkeet showing a way is much better than not showing it. At least he will whats going wrong and handle it. And there is no side effect of having any try/catch. – Murtaza Khursheed Hussain Nov 26 '14 at 13:50
  • I guess we'll have to agree to disagree. I dread to think how much terrible code there is partly due to examples like this encouraging the "ignore the error and just continue anyway" approach. At least you do check whether date is null... – Jon Skeet Nov 26 '14 at 13:53
  • @JonSkeet you are free to post your own awnser if you think mine is dreadful. I hope you will not post dreadful answer – Murtaza Khursheed Hussain Nov 26 '14 at 15:12
  • @MurtazaHussain: I didn't say it was a "dreadful" answer nor would I post another answer purely for the sake of something tangential like this - any more than I'd post a different answer if someone had used unconventional variable naming. I was merely encouraging a different approach, particularly based on my experience of seeing a *lot* of code where developers think that exception "handling" just consists of "catch, print the stack trace, continue as if nothing has happened". – Jon Skeet Nov 26 '14 at 16:04
1

I'm not sure whether I get your question right, but shouldn't the following work?

Date date=new Date("01/01/14 " + myTimeString);    // Example: 8:22:09 PM 
System.out.println("Formattet ="+new SimpleDateFormat("HH:mm").format(date));
Edi G.
  • 2,432
  • 7
  • 24
  • 33