Forum Discussion

AAB's avatar
AAB
Regular Contributor
6 years ago

Groovy How to change DateTime as dd-MM-yyyy

Hello,

 

I have to compare 2 different files that I'm doing with a Groovy script.

For the first file, the date is as dd-MM-yyyy. The second file is in yyyy-MM-dd.

How can I change the second date in the format of the first one please?

The code where this should be emplemented (2nd file) is as thus:

//------------Concepts - Validity - Dates
def getDates(it, dateToSearch) {
  // Find date in all validity nodes for this specific concept
  def dateNode = it.validity.find{it.startDate == dateToSearch}

  // Set dummy value to empty string
    def date = ""

  // If we found the date, get the value!
  if (dateNode != null) { date = dateNode.value }
  return date
}

I'm writing this to a textfile as such:

parsedJson.concepts.each {
	dynamic = ""
	addToCsvLine(it.keyValue);
	//log the startDate
	addToCsvLine(it.validity.startDate)
	// Remove last char ","
	dynamic = dynamic.substring(0, dynamic.length() - 1);
	
	//insert a new line
  	dynamic += '\n'
  	//write everything to the textfile as UTF-8
  	outputFile.append(dynamic, 'utf-8')
}
def addToCsvLine(element) {
dynamic += "\"" + element + "\","

Has someone an idea please?

Thanks in advance,

Kind regards,

AboveAndBeyond

  • nmrao  thanks for your response.

    I did it this way:

     

    //------------Concepts - Validity - Dates
    def convertDate(date) {
      SimpleDateFormat formatFromApi = new SimpleDateFormat("yyyy-MM-dd")
      Date parsedDate = formatFromApi.parse(date)
    
      SimpleDateFormat formatToGolden = new SimpleDateFormat("dd/MM/yyyy")
      String goldenDate = formatToGolden.format(parsedDate)
      return goldenDate
    }

    Kind regards,

    AboveAndBeyond

  • nmrao's avatar
    nmrao
    Champion Level 3
    Before comparing the dates, parse the string using respective format and convert it to Date object.

    For eg:

    def date = new Date().parse(format, stringDate)
    • AAB's avatar
      AAB
      Regular Contributor

      nmrao  thanks for your response.

      I did it this way:

       

      //------------Concepts - Validity - Dates
      def convertDate(date) {
        SimpleDateFormat formatFromApi = new SimpleDateFormat("yyyy-MM-dd")
        Date parsedDate = formatFromApi.parse(date)
      
        SimpleDateFormat formatToGolden = new SimpleDateFormat("dd/MM/yyyy")
        String goldenDate = formatToGolden.format(parsedDate)
        return goldenDate
      }

      Kind regards,

      AboveAndBeyond