代码示例
package main
import (
"fmt"
"time"
)
func main() {
// 时间戳转时间
timestamp := int64(1736420400)
t := time.Unix(timestamp, 0)
fmt.Println(t.Format("2006-01-02 15:04:05"))
// 时间转时间戳
loc, _ := time.LoadLocation("Asia/Shanghai")
t2, _ := time.ParseInLocation("2006-01-02 15:04:05",
"2025-01-09 15:00:00", loc)
fmt.Println(t2.Unix())
}
import java.time.*;
import java.time.format.DateTimeFormatter;
public class TimestampConverter {
public static void main(String[] args) {
// 时间戳转时间
long timestamp = 1736420400L;
Instant instant = Instant.ofEpochSecond(timestamp);
ZonedDateTime zdt = instant.atZone(ZoneId.of("Asia/Shanghai"));
System.out.println(zdt.format(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
// 时间转时间戳
LocalDateTime ldt = LocalDateTime.parse(
"2025-01-09 15:00:00",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
long ts = ldt.atZone(ZoneId.of("Asia/Shanghai"))
.toInstant().getEpochSecond();
System.out.println(ts);
}
}
use chrono::{DateTime, NaiveDateTime, TimeZone, Utc};
use chrono_tz::Asia::Shanghai;
fn main() {
// 时间戳转时间
let timestamp = 1736420400_i64;
let dt = Shanghai.timestamp_opt(timestamp, 0).unwrap();
println!("{}", dt.format("%Y-%m-%d %H:%M:%S"));
// 时间转时间戳
let naive = NaiveDateTime::parse_from_str(
"2025-01-09 15:00:00",
"%Y-%m-%d %H:%M:%S"
).unwrap();
let dt2 = Shanghai.from_local_datetime(&naive).unwrap();
println!("{}", dt2.timestamp());
}