-2

I'm formatting Date to String without symbols :,/,- using SimpleDateFormat, but it formats it strangely.

Here's my code :

public static String getFormatedDate(Date date, String format) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
    return simpleDateFormat.format(date);
}

And I call it like this :

DateUtil.getFormatedDate(new Date(), "DDMMYYYYHHMMSS")

Return of the call is incorrect 2540920170909379 it should look like this 11092017093405 = 11/09/2017 09:34:05

  • Watch the case of those format pattern letters. `d` and `D` doesn’t mean the same. Neither `y` and `Y`, etc. – Ole V.V. Sep 11 '17 at 13:34
  • 1
    Tell us, why are you still sticking to the outdated `SimpleDateFormat` class? Telling from the number of questions on Stack Overflow, this class seems to be causing lots of confusion and trouble. I recommend you throw is´t overboard and instead use [the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). It’s much nicer to work with. Its class for formatting is `DateTimeFormatter`. – Ole V.V. Sep 11 '17 at 13:37
  • 1
    If possible, use standard ISO 8601 formats rather than devising your own. – Basil Bourque Sep 12 '17 at 06:46
  • 1
    `ZonedDateTime.now().format( DateTimeFormatter.ofPattern( "ddMMuuuuHHmmss" ) )` – Basil Bourque Sep 12 '17 at 06:50

3 Answers3

3

Try the following;

DateUtil.getFormatedDate(new Date(), "ddMMyyyyHHmmss");

See java doc for complete format

shazin
  • 21,379
  • 3
  • 54
  • 71
2

Maybe the wrong output is because you are not using the correct date-time formatting pattern. You can use these characters:

  • y = Year
  • M = Month in year
  • w = Week in year
  • W = Week in month
  • D = Day in year
  • d = Day in month
  • F = Day of week in month
  • E = Day in week
  • a = Am/pm marker
  • H = Hour in day (0-23)
  • k = Hour in day (1-24)
  • K = Hour in am/pm (0-11)
  • h = Hour in am/pm (1-12)
  • m = Minute in hour
  • s = Second in minute
  • S = Millisecond

You may want to use this pattern: ddMMyyyyHHmmss for getting "datetime" like output.

juzraai
  • 5,693
  • 8
  • 33
  • 47
1

Then in place of

DateUtil.getFormatedDate(new Date(), "DDMMYYYYHHMMSS")

you should provide the correct format

DateUtil.getFormatedDate(new Date(), "ddMMyyyyHHmmss")
Shriyansh Gautam
  • 1,084
  • 1
  • 7
  • 13