Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

datetime - Date Formatting - Dataweave

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

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

1 Reply

0 votes
by (71.8m points)

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"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...