Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I two date functions that I'm useing to convert Date/Times into another format.

Input_1: 02/01/21 11:00:00 AM
Input_2: 02/01/21  3:00:00 PM

Desired Output 1: 2021-02-01T11:00:00.000
Desired Output 2: 2021-02-01T15:00:00.000
fun date_time_format(d: LocalDateTime {format: "M/d/yy  h:mm:ss a"}) = d as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}

fun date_time_format2(d: LocalDateTime {format: "M/d/yyyy h:mm:ss a"}) = d as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}
concert_time: 
          try(() -> date_time_format(Input_1) )
          orElseTry(() -> date_time_format2(Input_1) )
          orElse null

My resoult is null when using Input_1 but when using Input_2 it's 2021-02-01T15:00:00.000

question from:https://stackoverflow.com/questions/66056166/date-formatting-dataweave

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
357 views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem is the spacing between the date and the time is not fixed in the input, but it is fixed in the pattern. Instead use the padding format character to fix the issue.

I don't like the way the functions seems to be doing an implicit type conversion with formatting. You are not really passing a LocalDateTime but a String. That makes the intention very obscure. I suspect it is not a good practice. I changed my example to use explicit conversions. You could convert the parameter to LocalDateTime explicitly before invoking the function if you prefer it.

fun date_time_format(d: String) = 
    (d as LocalDateTime {format: "M/d/yy pph:mm:ss a"}) 
        as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}

Output:

{
  "concert_time1": "2021-02-01T11:00:00.000",
  "concert_time2": "2021-02-01T15:00:00.000"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...