DB和Java时间日期的比较和转换

huangapple go评论78阅读模式
英文:

DB and java time date comparison and conversion

问题

Sure, here's the translated code snippet:

public void reTrigger() {
    Date date1 = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH.mm.ss");

    String squery = "select newValue from SAVE_TXN WHERE ROWID = 1"; // newValue is of type nvarchar2

    String newValue = parser.getValueOf("newValue"); // parser is another method which parses the squery
    String vidtime = sdf.format(newValue);
    String currentDate = sdf.format(date1);

    try {
        Date vidDate = sdf.parse(vidtime);
        Date currentDateParsed = sdf.parse(currentDate);

        long timeDifferenceMillis = currentDateParsed.getTime() - vidDate.getTime();
        long hoursDifference = timeDifferenceMillis / (60 * 60 * 1000);

        if (hoursDifference >= 120) {
            // The time difference is greater than or equal to 120 hours
            // Your code logic here
        } else {
            // The time difference is less than 120 hours
            // Your code logic here
        }
    } catch (ParseException e) {
        e.printStackTrace();
        // Handle parsing exception
    }
}

Please note that the provided code assumes that the parser.getValueOf("newValue") method returns a valid date-time string in the format 'yyyy/MM/dd HH.mm.ss'. The code then parses both the fetched newValue and the current date, calculates the time difference in hours, and performs the comparison to check if the time difference is greater than or equal to 120 hours.

英文:

I am getting a variable newValue in java as

public void reTrigger() {
    Date date1 = new Date();
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH.mm.ss");

    squery: "select newValue from SAVE_TXN WHERE ROWID = 1"
(newValue is of type nvarchar2)

    String vidtime = sdf.format(parser.getValueOf("newValue")); //parser is another method which parses the squery 
String currentDate = sdf.format(date1);
}

Now newvalue contains date and time like: '2020/05/17 18.30.44' in DB, which I am fetching into vidtime.

Now I want to subtract this vidtime with currentDate in java and check whether it is greater than or equals to 120 hours or not. How to proceed ?

答案1

得分: 3

你正在使用多年前被现代 java.time 类取代的糟糕的日期时间类,这是在采纳 JSR 310 时完成的。

从数据库中检索日期时间值时,应该将其作为日期时间对象而不是字符串进行。从 JDBC 4.2 开始,我们可以在数据库中使用 java.time 类。请参阅 PreparedStatement::setObjectResultSet::getObject

对于类型为:

  • TIMESTAMP WITH TIME ZONE 的数据库列,应检索为 OffsetDateTime(遗憾的是,JDBC 4.2 中没有支持更常用的 InstantZonedDateTime 类)。

  • TIMESTAMP WITHOUT TIME ZONE 的数据库列,应检索为 LocalDateTime

如果面对字符串输入,可以使用 DateTimeFormatter 类进行解析。

您的输入缺少时区或偏移量指示器。因此,我们必须将其解析为 LocalDateTime

DateTimeFormatter f = DateTimeFormatter.ofPattern("uuuu/MM/dd HH.mm.ss");
LocalDateTime ldt = LocalDateTime.parse(input, f);

捕获当前时刻需要一个时区。对于任何给定的时刻,日期和每天的时间因时区而异。

ZoneId z = ZoneId.of("America/Montreal");
ZonedDateTime now = ZonedDateTime.now(z);

我们无法将当前时刻(zdt)与您的输入 ldt 进行比较。您的输入和 LocalDateTime 对象并不代表一个时刻,它们不是时间线上的特定点。以您的示例 2020/05/17 18.30.44 为例。我们无法确定这是指东京、图卢兹还是托莱多的当地时间下午 6:30,这些是时间线上几个小时之间的不同时刻。

因此,根据您提供的内容,问题无法解决。

如果您确切知道输入字符串的时区意图,请应用时区以生成 ZonedDateTime

ZoneId zIntended = ZoneOf.of("Africa/Tunis");
ZonedDateTime then = ldt.atZone(zIntended);

将经过的时间计算为 Duration

Duration d = Duration.between(now, then);
if (d.toHours() > 120) { ... }
英文:

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes with the adoption of JSR 310.

You should be retrieving date-time values from the database as date-time objects rather than strings. As of JDBC 4.2, we can exchange java.time classes with the database. See PreparedStatement::setObject and ResultSet::getObject.

For a database column of type:

  • TIMESTAMP WITH TIME ZONE, retrieve as a OffsetDateTime (support for the more commonly used Instant and ZonedDateTime classes was unfortunately and mysteriously omitted from JDBC 4.2).

  • TIMESTAMP WITHOUT TIME ZONE, retrieve as a LocalDateTime.

If faced with a string input, parse using DateTimeFormatter class.

Your input lacks an indicator of time zone or offset-from-UTC. So we must parse as a LocalDateTime.

DateTimeFormatter f = DateTimeFormatter.ofPattern(  "uuuu/MM/dd HH.mm.ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;

Capturing the current moment requires a time zone. For any given moment, the date and the time-of-day vary around the globe by zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;

We cannot compare this current moment (zdt) to your input, the ldt. Your input and a LocalDateTime object do not represent a moment, are not a specific point on the timeline. Take your example, 2020/05/17 18.30.44. We cannot know if that means 6:30 PM on the 17th in Tokyo, in Toulouse, or in Toledo – all different moments, several hours apart on the timeline.

So your Question as written cannot be solved.

If you know for certain that a time zone was intended for your input string, apply a time zone to produce a ZonedDateTime.

ZoneId zIntended = ZoneOf.( "Africa/Tunis" ) ;
ZonedDateTime then = ldt.atZone( zIntended ) ;

Calculate elapsed time as a Duration.

Duration d = Duration.between( now , then ) ;
if( d.toHours() > 120 ) { … }

答案2

得分: 1

也许类似这样的:

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Test {
    public static void main(String[] args) {
        final LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        final LocalDateTime dateToCompare = LocalDateTime.parse("2020-05-28 02:05:45", formatter);
        final long hours = Duration.between(now, dateToCompare).toHours();
        System.out.print(hours);
    }
}
英文:

Maybe something like this :

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Test {
    public static void main(String[] args) {
        final LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        final LocalDateTime dateToCompare = LocalDateTime.parse("2020-05-28 02:05:45",formatter);
        final long hours = Duration.between(now, dateToCompare).toHours();
        System.out.print(hours);
    }
}

huangapple
  • 本文由 发表于 2020年5月29日 22:45:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/62088595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定