
[英]How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"
[英]How do I get current system time in IST format and compare it to a time in HH:mm:ss format (which is in String datatype)? solution in java language
SimpleDateFormat time_formatter = new SimpleDateFormat("HH:mm:ss");
String current_time_str = time_formatter.format(System.currentTimeMillis());
Date currentTime = time_formatter.parse(current_time_str);
Date userTime = time_formatter.parse(timeSlots);
当我这样做时,我得到不正确的结果,因为服务器时间是 UTC 格式。
LocalTime
.parse( input )
.isBefore(
LocalTime.now( ZoneId.of( "Asia/Kolkata" ) )
)
您正在使用几年前被 JSR 310 中定义的现代java.time类取代的糟糕的日期时间类。切勿使用SimpleDateFormat
或Date
。
捕捉与 UTC 零时分秒的偏移量所见的当前时刻。
Instant instant = Instant.now() ;
调整到时区。
IST
不是实时时区。 这种 2-4 个字母的缩写只是一个粗略的指标,表明某个地区是否使用夏令时 (DST)。 这些缩写不规范,甚至不是唯一的! 例如, IST
通常用于表示爱尔兰标准时间和印度标准时间。 这些缩写仅用于向 5e 展示,绝不用于业务逻辑、数据存储、数据交换、日志记录或调试。
实时时区使用Continent/Région
格式命名。
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
将我们的时刻调整到那个区域。 时间线上的同一点,但通过该地区人们使用的挂钟时间可以看出。
ZonedDateTime zdt = instant.atZone( z ) ;
提取一天中的时间。
LocalTime currentTimeOfDayKolkata = zdt.toLocalTime() ;
解析一天中的输入时间。 无需指定格式模式,因为您的输入符合java.time类中默认使用的 ISO 8601 标准。
LocalTime localTimeInput = LocalTime.parse( input ) ;
做你的比较。
boolean isInputBeforeCurrentTimeOfDayKolkata = localTimeInput.isBefore( currentTimeOfDayKolkata ) ;
请注意,在这段代码中,我们没有依赖 JVM 当前的默认时区。 我们的计算机是否设置为 UTC 时间或Africa/Timbuktu
是无关紧要的。
所有这些已经在 Stack Overflow 上多次介绍过。 搜索以了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.