在一个小程序中,我需要判断该程序是否是当天第一次登陆,所以我使用了一个LastLogintime的String类型的数据来保存上次登陆的时间,使用Java的Date类再简单的封装出一个DateUtils类,public static String getNowtime() ()方法是其中获取当前时间的一个方法,返回时间格式是yyyy/MM/dd。
public static String getNowtime() { return new SimpleDateFormat("<span style="font-size:18px;">yyyy/MM/dd</span>").format(new Date()); }
当我使用 LastLogintime == DateUtils.getNowtime()来判断时,无法得出正确的结果。
查找原因发现 :不能使用 == 来判断,而应该使用String类的equals方法来判断。==是用来判断两个引用是否绑定在同一个对象上。而equals是用来判断两个对象内的内容是否相同。
C++的string类由于将 == 操作符重载了,所以可以使用 == 来判断两个字符串是否相等,由于java和C++的一些差异,需要注意。
参考:
http://www.cnblogs.com/shenliang123/archive/2012/04/16/2452156.html
http://docs.oracle.com/javase/8/docs/api/
Core Java Volume I--Fundamentals 9th Edition