比较日期? [英] Comparing dates?

查看:124
本文介绍了比较日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较Android中的两个日期,但即时通讯

I’m trying to compare two dates in Android but im getting this

当我写这篇文章时

    SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
    String valid_until = "26052018";
    final Date strDate = sdf.parse(valid_until);

如果我尝试像这样捉住

我无法比较日期,因为它说我没有声明 strDate

I can’t compare the date because it says I didn't declared strDate.

推荐答案

tl; dr



您的问题不是真正的比较日期。您的问题是尝试从其范围之外引用局部变量。

tl;dr

Your problem is not really about comparing dates. Your problem is trying to reference a local variable from outside its scope.

在您的 onClick 方法中尝试使用 strDate

In your onClick method where you try to use strDate:

if( new Date().after( strDate ) )

...没有这样的变量 strDate 在范围内。方法看不到其他方法(*)中定义的局部变量。这就是为什么将它们称为本地的原因,它们不存在于定义它们的方法之外。

…there is no such variable strDate within scope. Methods do not see local variable defined within other methods(*). That is why they are called "local", they do not exist outside the method that defined them.

范围可以更窄。在大括号内声明的局部变量(例如在 if 语句上)不在这些大括号内。

Scope can be even narrower. Local variables declared inside curly braces, such as on an if statement, do not exist outside those curly braces.

要通过其他方法访问 strDate ,必须使其可用。一种方法是在调用方法时将变量作为参数传递。另一种方法是,如果您填充和使用变量的两个地方都在同一个类中,则将该变量声明为该类的成员。

To access strDate from another method, you must make it available it available. One way is to pass the variable as an argument when calling the method. Another way is to declare the variable as a member of the class, if both places where you populate and use the variable live within the same class.

正如其他人指出的那样,您应该避免麻烦的旧日期时间类,例如 java.util.Date 。这些在几年前被业界领先的 java.time 类所取代。

As others noted, you should avoid the terribly troublesome old date-time classes such as java.util.Date. These were supplanted years ago by the industry-leading java.time classes.

LocalDate.parse(
    "26052018" , 
    DateTimeFormatter.ofPattern( "ddMMuuuu" )
)

搜索堆栈溢出以了解如何将字符串解析为 LocalDate 对象。

Search Stack Overflow to learn about parsing strings into LocalDate objects.

并避免使用问题中的自定义日期格式。尽可能使用标准的ISO 8601格式。对于仅日期的值,该值为YYYY-MM-DD。再次,搜索堆栈溢出以学习。

And avoid using custom date formats as seen in your Question. Whenever possible, stick with standard ISO 8601 formats. For a date-only value, that would be YYYY-MM-DD. Again, search Stack Overflow to learn.

LocalDate.parse( "2018-05-26" )






(*)方法有一些回旋方式,可以看到其他方法中定义的局部变量。这些包括反射/自省和内部类。但是它们是特殊情况。


(*) There are some roundabout ways for methods to see local variables defined in other methods. These include reflection/introspection and inner classes. But they are special cases.

这篇关于比较日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆