sey eeet
sey eeet

Reputation: 258

how to find the time difference in terms of day or hours?

I was wondering if I can somehow find the time difference between two times in pine script? For example: Can I find the difference between timestamp(2020,12,1,0,0) and time in terms of hours of days?

Upvotes: 1

Views: 1588

Answers (1)

mr_statler
mr_statler

Reputation: 2161

Since they are both returns a UNIX time in milliseconds, you can subtract one from the other and get the difference between them in milliseconds. From there you can use math to calculate how many weeks/day/hours are there in this amount of milliseconds.

I wrote a simple function to do so:

calculate_difference_between(start, end) =>
    weeksBetween = (end - start) / (1000*60*60*24*7)
    daysBetween = (weeksBetween - math.floor(weeksBetween)) * 7
    hoursBetween = (daysBetween - math.floor(daysBetween)) * 24
    minutesBetwenn = (hoursBetween - math.floor(hoursBetween)) * 60
    [math.floor(weeksBetween), math.floor(daysBetween), math.floor(hoursBetween), math.floor(minutesBetwenn)]

You can use this function like in this example:

//@version=5
indicator("My script", overlay = true)

t1 = timestamp(2020,12,1,0,0)
t2 = time

calculate_difference_between(start, end) =>
    weeksBetween = (end - start) / (1000*60*60*24*7)
    daysBetween = (weeksBetween - math.floor(weeksBetween)) * 7
    hoursBetween = (daysBetween - math.floor(daysBetween)) * 24
    minutesBetwenn = (hoursBetween - math.floor(hoursBetween)) * 60
    [math.floor(weeksBetween), math.floor(daysBetween), math.floor(hoursBetween), math.floor(minutesBetwenn)]


[weeks, days, hours, minutes] = calculate_difference_between(t1, t2)

if barstate.islast
    label.new(bar_index, high, "Weeks: " + str.tostring(weeks) + ", Days: " + str.tostring(days) + ", Hours: " + str.tostring(hours) + " ,Minutes: " + str.tostring(minutes))

Upvotes: 4

Related Questions