How to make the date type be defined as Date, and not as String?

319 views Asked by At

In my json there is a field with the value "01.05.2021 00:00:00", I need the type to be defined as Date, but it is defined as "String" because of the quotes, apparently. How do I make sure the type is "Date" and not String? I can change String to Date, but how can I do it in the list obtained from JSON?

Example as now: value 01.05.2021 00:00:00 typeMap String value 6 typeMap Integer

   def getTypeDef(def value) {
        (value instanceof BigDecimal) ? "Double" : value.getClass().simpleName
    }
 def list = jsonSlurper.parseText JSON
 def typeMap = [:].withDefault { key -> "String" }
            list.each { map ->
                map.each { key, values ->
                    if (values != null) {
                        typeMap[key] = getTypeDef(values)
                        println('value ' + values + ' typeMap ' + typeMap[key])
                        //typeMap[key] = values.getClass().simpleName
                    }
                }
            }
def types = names.collect { name -> typeMap[name] } 

I can do it like this, but the problem is that the value will still be a string, not a date, but I will get Date in println.

    def getTypeDef(def value) {
        if (value ==~ /^(0?[1-9]|[12][0-9]|3[01])[\\/\-.](0?[1-9]|1[012])[\\/\-.]\d{4}\s[0-2]?[0-9]:[0-5][0-9]:[0-5][0-9]\u0024/){
            (value instanceof String) ? "Date" : value.getClass().simpleName
        }
        else{
            (value instanceof BigDecimal) ? "Double" : value.getClass().simpleName
        }

    }
1

There are 1 answers

1
bimjhi On

Here is a method to convert a String being in a "2020.04.19 12:10:36" format to Date type.

Input:

def date = convertStringToDate("2020.04.19 12:10:36")
def sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss")
println sdf.format(date)

Output:

2020.04.19 12:10:36

Code:

import java.text.SimpleDateFormat;
import java.util.Date;
import java.time.*;
import java.time.LocalDateTime;  
import java.time.format.DateTimeFormatter;

def convertStringToDate(String str) {
    //needed format: String dateStr = "2020.04.19 12:10:36";
    DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss");
    LocalDateTime dateTime = LocalDateTime.parse(str, pattern);
    Date convertedDatetime = Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
    assert convertedDatetime instanceof Date
    return convertedDatetime
}
assert convertStringToDate("2020.04.19 12:10:36") instanceof Date

def date = convertStringToDate("2020.04.19 12:10:36")
def sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss")
println sdf.format(date)