3

Possible Duplicate:
String to Date in Different Format in Java

I want to convert String to Date in different Format.

String d = "07:33:01 PM 26/11/2011";

How can i covert it to 26/11-19h30?

Community
  • 1
  • 1
user1024858
  • 129
  • 3
  • 5
  • 11
  • 3
    Use `SimpleDateFormat`. Search this forum for this and you'll find many examples, and in fact you can start by looking at the "related" links on the right side, lower half of this very page. – Hovercraft Full Of Eels Nov 27 '11 at 13:26

4 Answers4

2
DateFormat formatter = new SimpleDateFormat("MM/dd-H\hm");
date = (Date)formatter.parse(d);

You will need to import java.util.* and import java.text.*

dotancohen
  • 30,064
  • 36
  • 138
  • 197
  • @Zakaria: I did not steal your answer, you might even notice that I posted mine before yours. – dotancohen Nov 27 '11 at 13:36
  • You edited the yours minutes after some code was posted. Anyway, we are in the a community oriented website : you could edit posts or comment them to improve them. There is no concurential goal. – Zakaria Nov 27 '11 at 13:42
  • But mine was first of all. Seriously, though this sort of question has been asked and answered so many times here, another similar question without the original poster showing his actual problem is really not much more than clutter. – Hovercraft Full Of Eels Nov 27 '11 at 13:42
  • totally agree lol come on guys, we are not children ... @HovercraftFullOfEels : this why i give it a point ;) – Zakaria Nov 27 '11 at 13:45
  • @dotancohen : I removed it to avoid this discussion. Anyway ... I could not a post where you suggested to import whatever lib : sorry, it's ridiculous. – Zakaria Nov 27 '11 at 13:48
2
String d = "07:33:01 PM 26/11/2011";
Date date = new SimpleDateFormat("d/MM-HH\hmm", Locale.ENGLISH).parse(d);
Zakaria
  • 14,892
  • 22
  • 84
  • 125
  • I have tried it. But it also can't.
    this is the my problem :
    java.text.ParseException: Unparseable date: "09:33:01 AM 26/11/2011" at java.text.DateFormat.parse(DateFormat.java:357)
    – user1024858 Nov 27 '11 at 13:36
  • 1
    Could you post the program you are using to print the answer ? What error did you get ? – Zakaria Nov 27 '11 at 13:38
  • Thank you very much Zakaria. I have done. Good luck!!! – user1024858 Nov 27 '11 at 13:43
1

Have a look at SimpleDateFormat. You can parse to custom date formats using this class.

mort
  • 12,988
  • 14
  • 52
  • 97
1
    String d = "07:33:01 PM 26/11/2011";

    SimpleDateFormat formatterIn = new SimpleDateFormat("hh:mm:ss a dd/MM/yyyy");
    SimpleDateFormat formatterOut = new SimpleDateFormat("dd/MM-HH'h'mm");
    Date date = formatterIn.parse(d);  

    System.out.println(formatterOut.format(date));

It converts to 26/11-19h33, do you want to round to 26/11-19h30?

Raul Guiu
  • 2,374
  • 22
  • 37