How to parse dates in multiple formats using SimpleDateFormat

前端 未结 12 1731
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 08:41

I am trying to parse some dates that are coming out of a document. It would appear users have entered these dates in a similar but not exact format.

here are the for

12条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 09:17

    Implemented the same in scala, Please help urself with converting to Java, the core logic and functions used stays the same.

    import java.text.SimpleDateFormat
    import org.apache.commons.lang.time.DateUtils
    
    object MultiDataFormat {
      def main(args: Array[String]) {
    
    val dates =Array("2015-10-31","26/12/2015","19-10-2016")
    
    val possibleDateFormats:Array[String] = Array("yyyy-MM-dd","dd/MM/yyyy","dd-MM-yyyy")
    
    val sdf =  new SimpleDateFormat("yyyy-MM-dd") //change it as per the requirement
      for (date<-dates) {
        val outputDate = DateUtils.parseDateStrictly(date, possibleDateFormats)
        System.out.println("inputDate ==> " + date + ", outputDate ==> " +outputDate + " " + sdf.format(outputDate) )
      }
    }
    

    }

提交回复
热议问题