4

I have a DateTime object and I want to print it with a given format, let's say yyyy-MM-dd.

I've tried

val date = DateTime.now()
val format = "yyyy-MM-dd"
println(date.formatted(format))

but got yyyy-MM-dd as if the format wasn't recognized.

I also tried

val formatter = new SimpleDateFormat(format)
println(

but got

Cannot format given Object as a Date java.lang.IllegalArgumentException: Cannot format given Object as a Date

How do I print the DateTime object in the format of my choosing?

Dotan
  • 6,602
  • 10
  • 34
  • 47
  • is it a joda DateTime? – pedrorijo91 May 07 '17 at 19:06
  • if so, have a look: http://stackoverflow.com/questions/20331163/how-to-format-joda-time-datetime-to-only-mm-dd-yyyy – pedrorijo91 May 07 '17 at 19:06
  • 1
    Possible duplicate of [How to format Joda-Time DateTime to only mm/dd/yyyy?](http://stackoverflow.com/questions/20331163/how-to-format-joda-time-datetime-to-only-mm-dd-yyyy) – pedrorijo91 May 07 '17 at 19:07
  • @pedrorijo91 although the answers overlap, the PO in that question asks about parsing a string, not a DateTime object – Dotan May 08 '17 at 07:30

1 Answers1

10

a date object has a toString(format: String) method.

date.toString(format)

2017-05-07

Dotan
  • 6,602
  • 10
  • 34
  • 47