gmt java date,如何使用Java查找GMT的时代格式当前时间

该代码示例展示了如何使用Java的SimpleDateFormat和TimeZone类获取GMT-7时区的当前时间,并将其转换为Unix时间戳。通过创建SimpleDateFormat对象设置日期格式,然后将日期转换为字符串,再解析回日期对象,最终获取时间戳。另一种方法是使用Calendar类直接获取Unix时间戳,简化了转换过程。
摘要由CSDN通过智能技术生成

I have written below code which is running, and giving output. But I'm not sure It's a right one.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Date date = new Date();

sdf.setTimeZone(TimeZone.getTimeZone("GMT-7"));

String value = sdf.format(date);

System.out.println(value);

Date date2 = sdf.parse(value);

long result = date2.getTime();

System.out.println(result);

return result;

The above code what I'm trying is, I just need to get the current time of GMT time zone and convert it as epoch format which is gonna used in Oracle db.

Can someone tell me that format, and the above code is right?

解决方案

Why not use Calendar class?

public long getEpochTime(){

return Calendar.getInstance(TimeZone.getTimeZone("GMT-7")).getTime().getTime()/1000; //( milliseconds to seconds)

}

It'll return the current Date's Epoch/Unix Timestamp.

Based on Harald's Comment:

public static long getEpochTime(){

return Clock.system(TimeZone.getTimeZone("GMT-7").toZoneId() ).millis()/1000;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值