File: julian.go

package info (click to toggle)
golang-github-sap-go-hdb 0.100.10-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 800 kB
  • sloc: python: 27; makefile: 5
file content (64 lines) | stat: -rw-r--r-- 1,834 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
Copyright 2017 SAP SE

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package protocol

import (
	"time"
)

const gregorianDay = 2299161                      // Start date of Gregorian Calendar as Julian Day Number
var gregorianDate = julianDayToTime(gregorianDay) // Start date of Gregorian Calendar (1582-10-15)

// timeToJulianDay returns the Julian Date Number of time's date components.
// The algorithm is taken from https://en.wikipedia.org/wiki/Julian_day.
func timeToJulianDay(t time.Time) int {

	t = t.UTC()

	month := int(t.Month())

	a := (14 - month) / 12
	y := t.Year() + 4800 - a
	m := month + (12 * a) - 3

	if t.Before(gregorianDate) { // Julian Calendar
		return t.Day() + (153*m+2)/5 + 365*y + y/4 - 32083
	}
	// Gregorian Calendar
	return t.Day() + (153*m+2)/5 + 365*y + y/4 - y/100 + y/400 - 32045
}

// JulianDayToTime returns the correcponding UTC date for a Julian Day Number.
// The algorithm is taken from https://en.wikipedia.org/wiki/Julian_day.
func julianDayToTime(jd int) time.Time {
	var f int

	if jd < gregorianDay {
		f = jd + 1401
	} else {
		f = jd + 1401 + (((4*jd+274277)/146097)*3)/4 - 38
	}

	e := 4*f + 3
	g := (e % 1461) / 4
	h := 5*g + 2
	day := (h%153)/5 + 1
	month := (h/153+2)%12 + 1
	year := (e / 1461) - 4716 + (12+2-month)/12

	return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
}