Groovy web console

subscribe to the feed Subscribe
to this
site

String date parsing

Published 1 month ago by Rutger de Vries with tags data
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import java.text.SimpleDateFormat
import java.util.Date

//date = '2020-01-01'
//date = '2020-1-1'
//date = '01-01-2021'
//date = '1-1-2021'
//date = '01-01-22'
//date = '1-1-22'
//date = '2023/01/01'
//date = '01/01/2024'
//date = '01/01/25'
//date = '1/1/25'

//date = ''

formattedDate = formatDate(date)

def formatDate(date){
	if(date != ''){
  if(date.contains('-')){
   if(date.split('-').first().size() == 4){
    parsedDate = new SimpleDateFormat("yyyy-MM-dd").parse(date) 
    newDate = new SimpleDateFormat("yyyy-MM-dd").format(parsedDate)
   } else if (date.split('-').last().size() == 4){
    parsedDate = new SimpleDateFormat("dd-MM-yyyy").parse(date) 
    newDate = new SimpleDateFormat("yyyy-MM-dd").format(parsedDate)
   } else {
    parsedDate = new SimpleDateFormat("dd-MM-yy").parse(date) 
    newDate = new SimpleDateFormat("yyyy-MM-dd").format(parsedDate)
   }
  }
  if(date.contains('/')){
   if(date.split('/').first().size() == 4){
    parsedDate = new SimpleDateFormat("yyyy/MM/dd").parse(date) 
    newDate = new SimpleDateFormat("yyyy-MM-dd").format(parsedDate)
   } else if (date.split('/').last().size() == 4){
    parsedDate = new SimpleDateFormat("dd/MM/yyyy").parse(date) 
    newDate = new SimpleDateFormat("yyyy-MM-dd").format(parsedDate)
   } else {
    parsedDate = new SimpleDateFormat("dd/MM/yy").parse(date) 
    newDate = new SimpleDateFormat("yyyy-MM-dd").format(parsedDate)
   }   
  }
	} else {
  newDate = date
	}
	return newDate
}