Home > OS >  How to generate a DATETIME based on 6 integers: yyyy, MM, dd, HH, mm, ss?
How to generate a DATETIME based on 6 integers: yyyy, MM, dd, HH, mm, ss?

Time:08-31

For example, yyyy=2022, MM=8, dd=25, HH=14, mm=50, ss=30, how can I get 2022.08.25T14:50:30?

CodePudding user response:

Use concat to concatenate these integers into strings and parse with temporalParse (datetimeParse)

yyyy=2022
MM=8
dd=25
HH=14
mm=50
ss=30

s = concat([yyyy, MM, dd, HH, mm, ss], "-")
d = datetimeParse(s, "yyyy-MM-dd-HH-mm-ss")

There are two ways to solve this problem. As mentioned above, one is to use concat to concatenate integers into strings and then convert it to a DATETIME (func 1).

You can also convert these integers using func2.

yyyy=2022
MM=8
dd=25
HH=14
mm=50
ss=30

def func1(yyyy, MM, dd, HH, mm, ss){
    return temporalParse(concat([yyyy, MM, dd, HH, mm, ss], "-"), "yyyy-MM-dd-HH-mm-ss")
}
def func2(yyyy, MM, dd, HH, mm, ss){
    return datetime(date(month(yyyy*12) MM-1) dd-1) HH*3600 mm*60 ss
}

timer func1(yyyy, MM, dd, HH, mm, ss)
timer func2(yyyy, MM, dd, HH, mm, ss)

Output:

Time elapsed: 0.078 ms

Time elapsed: 0.072 ms

There is not much difference in performance.

If there is a large amount of data, i.e., yyyy, MM, dd, HH, mm, and ss are vectors, you can use func3.

n = 10000000
yyyy=take(2022,n)
MM=rand(1..12,n)
dd=rand(1..28,n)
HH=rand(24,n)
mm=rand(60,n)
ss=rand(60,n)
def func3(yyyy, MM, dd, HH, mm, ss){
    return temporalParse((string(yyyy) "-" string(MM) "-" string(dd) "-" string(HH) "-" string(mm) "-" string(ss)),"yyyy-MM-dd-HH-mm-ss")
}

timer func2(yyyy, MM, dd, HH, mm, ss)
timer func3(yyyy, MM, dd, HH, mm, ss)

Time elapsed: 203.697 ms

Time elapsed: 9571.486 ms

CodePudding user response:

const date = new Date();
console.log(date.toISOString());

gave me this: "2022-08-30T02:32:49.627Z"

then you can remove the last 2 characters off the end. You would also need to fiddle around with time zones to figure out what the difference between your time and the ISO format which I think is based off of toUTCString(), and you would need to account for day light savings.

  • Related