Source code

Download source archive ↓

src/CommonUtil.scala

1package cn.piflow.bundle.flux.util
2
3
4import scala.math.{Pi => PI}
5
6import java.text.SimpleDateFormat
7import scala.math.{acos, atan, sin, tan}
8
9object CommonUtil {
10  //将传入的年月日字符串转换成时间戳
11  def toTimeStamp(year: String, month: String, day: String, hour: String): Long = {
12    val fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
13    var tm = ""
14    if (hour.contains(".5")) {
15      tm = s"${year}-${month}-${day} ${hour.split("\\.")(0)}:30:00"
16    } else {
17      tm = s"${year}-${month}-${day} ${hour.split("\\.")(0)}:00:00"
18    }
19    val dt = fm.parse(tm)
20    dt.getTime
21  }
22
23
24  /**
25   * 根据经纬度计算日落日出时间
26   *
27   * @param longitude
28   * @param latitude
29   * @param J 日序数,为1到365或366之间整数
30   * @return
31   */
32  def SunriseAndSunsetTime(longitude: Double, latitude: Double, J: Int): String = {
33    //    计算赤纬正切值
34    val δ = 0.409 * sin((2 * PI * J / 365) - 1.39)
35    //    计算赤纬(弧度)
36    val δ_rad = atan(δ)
37    //    计算日照时间
38    val t = 24 * acos((-1) * tan(latitude * PI / 180) * tan(δ_rad)) / PI
39    //    日出时间(以北京时间计)
40    val sunrise = (12 - t / 2) - ((longitude - 120) * 24 / 360)
41
42    //    日落时间(以北京时间计)
43    val sunset = (12 + t / 2) - ((longitude - 120) * 24 / 360)
44
45    sunrise.formatted("%.2f") + "," + sunset.formatted("%.2f")
46  }
47
48
49}