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
65
66
67
68
69
70
71
72
73
package tools.timestamp
import java.text.SimpleDateFormat
import java.time.format.{DateTimeFormatter, DateTimeFormatterBuilder}
import java.time.{OffsetDateTime, ZoneId, ZonedDateTime}
import java.util.Date
import scala.language.postfixOps
/**
* Created with IntelliJ IDEA.
* Class: DateHelper
* Description: 时间处理类
* User: lin
* Date: 2021-07-19
* Time: 16:17
*/
object DateHelper {
private[this] val DATE_TIME_FORMATTER: DateTimeFormatter = new DateTimeFormatterBuilder().appendOptional(DateTimeFormatter.ISO_DATE_TIME).appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME).appendOptional(DateTimeFormatter.ISO_INSTANT).appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SX")).appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssX")).appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).toFormatter.withZone(ZoneId.systemDefault())
/**
* 把时间字符串转换成标准时间
*
* @param str 时间字符串
* @return 标准时间
*/
def parseDateTimeString(str: String): OffsetDateTime = ZonedDateTime.from(DATE_TIME_FORMATTER.parse(str)).toOffsetDateTime
/**
* 时间戳转换成时间
*
* @param timestamp 时间戳(毫秒)
* @param pattern 时间格式
* @return 指定格式的日期
*/
def parseTimestampToDataTime(timestamp: Long, pattern: String): String = new SimpleDateFormat(pattern).format(new Date(formatTimestamp(timestamp)))
/**
* 时间戳转换成时间(默认格式)
*
* @param timestamp 时间戳(毫秒)
* @return 默认格式“yyyy-MM-dd HH:mm:ss”
*/
def parseTimestampToDataTime(timestamp: Long): String = parseTimestampToDataTime(formatTimestamp(timestamp), "yyyy-MM-dd HH:mm:ss")
/**
* 把时间格式定为毫秒,如果不是毫秒 x1000
*
* @param timestamp 时间戳
* @return 格式化时间戳
*/
def formatTimestamp(timestamp: Long): Long = if (timestamp.toString.length < 13) timestamp * 1000 else timestamp
/**
* 把时间转换成时间戳
*
* @param time 时间
* @param pattern 时间格式
* @return 时间戳
*/
def parseDateTimeToTimestamp(time: String, pattern: String): Long = new SimpleDateFormat(pattern).parse(time).getTime
/**
* 把时间转换成时间戳(默认格式)
*
* @param time 时间
* @return 时间戳(默认格式:”yyyy-MM-dd HH:mm:ss“)
*/
def parseDateTimeToTimestamp(time: String): Long = parseDateTimeToTimestamp(time, "yyyy-MM-dd HH:mm:ss")
}