How can I convert the dd/mm/yyyy to yyyymmdd format and also dd/m/yyyy to yyyymmdd format by using joda time in Scala.
am using this dependency
"joda-time" % "joda-time" % "2.9.9",
This answer already answers your question in Java, but here it is translated into Scala:
import org.joda.time.DateTime
import org.joda.time.format.{DateTimeFormat, DateTimeFormatter}
// define original date format
val originalFormat: DateTimeFormatter = DateTimeFormat.forPattern("dd/MM/yyyy")
val input: DateTime = originalFormat.parseDateTime("02/09/2017")
// define new format
val newFormat: DateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd")
val output: String = newFormat.print(input) // 20170902
This code will already account for missing a leading 0
from your date (ie it will see 02/9/2017
and 2/9/2017
as the same thing). It will not predict missing parts of the year though, so 2/9/17
will be outputted as 00170902
instead of 20170902
.
As the answer I linked to earlier mentions though, you can just use java.time
to do the same thing:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
val originalFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy")
val input = LocalDate.parse("02/09/2017", originalFormat)
val newFormat = DateTimeFormatter.ofPattern("yyyyMMdd")
val output = input.format(newFormat)
import org.joda.time.DateTime
import org.joda.time.format._
val fmt = DateTimeFormat.forPattern("dd/mm/yyyy")
val dt = fmt.parseDateTime("02/02/2017")
val fmt2 = DateTimeFormat.forPattern("yyyymmdd")
fmt2.print(dt)