How to check if the date is today or not - android

I am getting the current date like below:
public void getCurrentDate(View view) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("yyyy / MM / dd ");
String strDate = "Current Date : " + mdformat.format(calendar.getTime());
display(strDate);
}
private void display(String num) {
TextView textView = (TextView) findViewById(R.id.current_date_view);
textView.setText(num);
}
But I want to check whether the date is today's date or not. But I am not getting how to check that.

You can do as #aliaksei's answer, which works fine. But in Android you can also use java.time (API level 26) or ThreetenABP if java.time is not available.
But first you must consider the fact that "today's date" is relative. Now, at this very moment, each part of the world might be in a different "today". In America and Europe it's April 10th, but in some parts of the Pacific it's already April 11th.
You can choose a specific timezone, or just use the device's zone, which I think it's the case. In this case, just use the JVM default timezone.
Then you use the ThreetenABP to convert the Calendar to a LocalDate and then compare with today's date:
// calendar I want to check
Calendar cal = ...
// convert to LocalDate
LocalDate date = DateTimeUtils.toZonedDateTime(cal).toLocalDate();
// compare with today (now() is using the JVM default timezone)
if (date.isEqual(LocalDate.now(ZoneId.systemDefault()))) {
// today
}

public static boolean isSameDay(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("The dates must not be null");
}
return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
}
Or you could use the DateUtils class that this snippet is from :)

Related

Getting Current date and time

I tried to access current datetime in android application as follows :
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
//long time = System.currentTimeMillis();
Date date2 = new Date(seconds);
Log.d(">>>>>>>Current Date : ",""+date2);
It gives me date and time with the year 1970 as follows :
>>>>>>>Current Date :﹕ Thu Jan 01 05:30:00 GMT+05:30 1970
but, It should be 2015 instead of 1970.
What the problem is ?
I have solved above problem from solution provided. Atually, I am generating notification as the datetime value from the databse matches to the current datetime value. but, it does not generating notification.
My code is as follows :
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
doAsynchTask = new TimerTask() {
#Override
public void run() {
Log.d("Timer Task Background", "Timer task background");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
long time = System.currentTimeMillis();
Date dateCurrent = new Date(time);
Log.d(">>>>>>>Current Date : ", "" + dateCurrent);
getListData();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
Date dateFromDatabase;
for (int i = 0; i < remiderList.size(); i++) {
try {
System.out.print("+++" + remiderList.get(i).toString());
dateFromDatabase = formatter.parse(remiderList.get(i).toString());
Log.d(">>>>>Database date : ", "" + dateFromDatabase);
if (dateCurrent.equals(dateFromDatabase)) {
Toast.makeText(getApplicationContext(), "Date matched", Toast.LENGTH_LONG).show();
displayNotification();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
};
timer.schedule(doAsynchTask, 0, 1000);
}
public void displayNotification() {
Notification.Builder builder = new Notification.Builder(MyRemiderService.this);
Intent intent1 = new Intent(this.getApplicationContext(),
HomeActivity.class);
Notification notification = new Notification(R.drawable.notification_template_icon_bg,
"This is a test message!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(
this.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha)
.setContentTitle("ContentTitle").setContentText("this for test massage")
.setContentIntent(pendingNotificationIntent);
notification = builder.getNotification();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
/* notification.setLatestEventInfo(this.getApplicationContext(),
"AlarmManagerDemo", "This is a test message!",
pendingNotificationIntent);*/
mManager.notify(0, notification);
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void getListData() {
remiderList = dbHelper.getAllRemiders();
}
I have checked both the values in Logcat as follows :
09-15 17:50:00.629 17915-17927/? D/>>>>>>>Current Date :﹕ Tue Sep 15 17:50:00 GMT+05:30 2015
09-15 17:50:00.637 17915-17927/? D/>>>>>Database date :﹕ Tue Sep 15 17:50:00 GMT+05:30 2015
You have not set current date in calender object.
Calendar c = Calendar.getInstance();
c.setTime(new Date());
//Calendar.SECOND will return only seconds from the date
//int seconds = c.get(Calendar.SECOND);
long time = c.getTime();
Date date2 = new Date(time);
Log.d(">>>>>>>Current Date : ",""+date2);
You can use SimpleDateFormat class to format the dates as follow
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
System.out.println(format.format(new Date()));
try this
private String getCurrentDateAndTime() {
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
return simple.format(new Date());
}
Avoid old date-time classes
You are using the old date-time classes bundled with the earliest versions of Java such as java.util.Date/.Calendar. They have proven to be poorly designed, confusing, and troublesome. Avoid them.
Among the many points of confusion is that a java.util.Date represents a calendar date and a time-of-day while a java.sql.Date pretends to represent only a date without any time-of-day although it does actually have a time-of-day just set to zeros (00:00:00.0).
java.time
The old date-time classes have been supplanted by the java.time framework. See Tutorial.
Java 8 and later: The java.time framework is built-in.
Java 7 & 6: Use the backport of java.time.
Android: Use this wrapped version of that backport.
java.sql
Eventually we should see JDBC drivers updated to deal with java.time types directly. Until then, we still need the java.sql types for getting data in/out of databases. But immediately call the new conversion methods added to the old classes to move into java.time types.
Instant
An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.
java.sql.Timestamp ts = myResultSet.getTimestamp( x );
Instant instant = ts.toInstant();
LocalDate
If you are trying to compare the date-portion of that date time to today’s date, use the LocalDate class. This class truly represents a date-only value without time-of-day and without time zone.
Time Zone
Note that a time zone is crucial to determining dates, as the date may vary around the world by time zone for any given moment. So before extracting the LocalDate we need to apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVM’s current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate today = LocalDate.now( zoneId );
if( today.isEqual( zdt.toLocalDate() ) {
…
}
Notice that nowhere in that code did we use Strings; all date-time objects instead.
Formatting Strings
To generate a String as a textual representation of the date-time value, you can call the toString methods to get text formatted using the ISO 8601 standard. Or specify your own formatting pattern. Better yet, let java.time do the work of localizing automatically. Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and such.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) ); // Or Locale.CANADA_FRENCH and so on.

How to compare current date with selected date in android with java

I am taking current date using the code like below
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
And I am selecting date using
CalendarView cal.setOnDateChangeListener(new OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth)
String s = +year + " : " + (month + 1) + " : " +dayOfMonth ;
and passing it on next activity as--
Intent in = new Intent(MainActivity.this, sec.class);
in.putExtra("TextBox", s.toString());
startActivity(in);
I want to check here if user selected previous date from current date
then give a message and don't go on next activity.
Use SimpleDateFormat:
If your date is in 31/12/2014 format.
String my_date = "31/12/2014"
Then you need to convert it into SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(my_date);
if (new Date().after(strDate)) {
your_date_is_outdated = true;
}
else{
your_date_is_outdated = false;
}
or
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(my_date);
if (System.currentTimeMillis() > strDate.getTime()) {
your_date_is_outdated = true;
}
else{
your_date_is_outdated = false;
}
I am providing the modern answer.
java.time and ThreeTenABP
Use LocalDate from java.time, the modern Java date and time API.
To take the current date
LocalDate currentDate = LocalDate.now(ZoneId.systemDefault());
System.out.println(currentDate);
When I ran this code just now, the output was:
2020-01-05
To get selected date in your date picker
int year = 2019;
int month = Calendar.DECEMBER; // but don’t use `Calendar`
int dayOfMonth = 30;
LocalDate selectedDate = LocalDate.of(year, month + 1, dayOfMonth);
System.out.println(selectedDate);
2019-12-30
Your date picker is using the same insane month numbering that the poorly designed and long outdated Calendar class is using. Only for this reason, in an attempt to produce readable code, I am using a constant from that class to initialize month. In your date picker you are getting the number given to you, so you have no reason to use Calendar. So don’t.
And for the same reason, just as in your own code I am adding 1 to month to get the correct month number (e.g., 12 for December).
Is the date in the past?
if (selectedDate.isBefore(currentDate)) {
System.out.println("" + selectedDate + " is in the past; not going to next activity");
} else {
System.out.println("" + selectedDate + " is OK; going to next activity");
}
2019-12-30 is in the past; not going to next activity
Converting to String and back
If you need to convert your selected date to a string in order to pass it through the Intent (I don’t know whether this is a requirement), use the toString and parse methods of LocalDate:
String dateAsString = selectedDate.toString();
LocalDate recreatedLocalDate = LocalDate.parse(dateAsString);
System.out.println(recreatedLocalDate);
2019-12-30
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Use below code,
Create a date object using date formator.
Compare date (There many way out to compare dates and one is mentioned here)
Open intent or make toast as you said message.
CalendarView cal.setOnDateChangeListener(new OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
String s = (month + 1) + "-" + dayOfMonth + "-" + year;
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Date dateSource = null;
Calendar cal = Calendar.getInstance();
Date sysDate = cal.getTime();
try {
dateSource = sdf.parse(s);
if(dateSource.compareTo(sysDate)>0){
Toast.makeToast("Selected worng date",Toast.SHOW_LONG).show();
}else{
Intent in = new Intent(MainActivity.this, sec.class);
in.putExtra("TextBox", s.toString());
startActivity(in);
}
}
catch (ParseException e) {
Loger.log("Parse Exception " + e);
e.printStackTrace();
}
}
}
Edit
You need a view xml having the calender defined in it. It can be a fragment or activity view xml file
Inflate the view in your Activity or fragment class.
View _rootView = inflater.inflate({your layout file},container, false);
Get the respective control java object from the xml like
cal = (CalendarView)_rootView.findViewById(R.id.calViewId);
Now call event listener on this cal object.
Try this lines of code, this may help. Cheers!!!
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = sdf.parse(enteredDate);
if (System.currentTimeMillis() > date.getTime()) {
//Entered date is backdated from current date
} else {
//Entered date is updated from current date
}
} catch (ParseException e) {
e.printStackTrace();
}

Android Timezone Ids are not matching with System Timezone Ids issue

I am working on timezones concept in Android.
I want to change the timezone of the Android tablet by taking the timezone from the App Variable in the application. I am getting the System TimeZones as the variable value i.e like
Dateline Standard Time
UTC-11
Samoa Standard Time
Hawaiian Standard Time
Alaskan Standard Time
Pacific Standard Time (Mexico)
Pacific Standard Time
US Mountain Standard Time
Mountain Standard Time (Mexico)
Mountain Standard Time
Central America Standard Time
Central Standard Time
Central Standard Time (Mexico)
Canada Central Standard Time
SA Pacific Standard Time
From Android case, I am getting Timezone Id's like
Africa/Harare
Africa/Johannesburg
Africa/Kigali
Africa/Lubumbashi
Africa/Lusaka
Africa/Maputo
Africa/Maseru
Africa/Mbabane
Africa/Tripoli
Asia/Amman
Asia/Beirut
Asia/Istanbul
Asia/Jerusalem
Asia/Nicosia
Asia/Tel_Aviv
CAT
EET
Egypt
Etc/GMT-2
Europe/Chisinau
Europe/Helsinki
and my code is
if (mCalendar != null) {
mCalendar = Calendar.getInstance();
}
else
{
String[] allTimeZones = TimeZone.getAvailableIDs();
Arrays.sort(allTimeZones);
for (int i = 0; i < allTimeZones.length; i++) {
System.out.println(allTimeZones[i]);
}
TimeZone tz = TimeZone.getTimeZone(String.valueOf(Jordan Standard Time));
mCalendar = Calendar.getInstance(tz);
String name = tz.getID();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " + name);
}
As 'Jordan Standard Time' is variable from application is not like Timezone of tablet available Id's, Timezone is not changing.
If I replace the Timezone with 'Africa/Tripoli' manually, the timezone is replacing with this one.
My issue now is I would like to convert the system timezones to Tablet Timezone Ids and display it in Android Application.
plz use this function that is display GMT Time display if you change timezone from you android phone.
public static String GetDateForGMTDate(String dateString) {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-mm-dd");
SimpleDateFormat formatter1 = new SimpleDateFormat(
"yyyy-mm-dd");
Date date = null;
try {
date = formatter.parse(dateString);
System.out.println(date);
System.out.println(formatter.format(date));
Calendar cal = Calendar.getInstance();
cal.setTime(date);
Log.i("Time zone", "gettime=" + cal.getTime());
cal.add(Calendar.MINUTE, (-1 * getTimeZoneDifference()));
Log.i("Time zone", "after gmt +gettime=" + cal.getTime());
date = cal.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return formatter1.format(date);
}
public static final int getTimeZoneDifference() {
long currentTime = System.currentTimeMillis();
int gmtcurrentOffset = TimeZone.getDefault().getOffset(currentTime);
int gmtOffset = TimeZone.getTimeZone("GMT").getOffset(currentTime);
int minuteDifference = (((gmtOffset - gmtcurrentOffset) / 1000) / 60);
return minuteDifference;
}
use 1st function and pass any date with yyy-mm-dd formate as a string. and that function will return gmt formate real date-time.
i already use it.
its working fine.i hope its useful to you.

Cant fetch current time, date showing year as 1970

public static final String inputFormat = "HH:mm";
private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;
LINE 5:
private String compareStringOne = String.valueOf(SetTimeActivity.intFromTimeH)+ ":"+ String.valueOf(SetTimeActivity.intFromTimeM) ;
LINE 6:
private String compareStringTwo = String.valueOf(SetTimeActivity.intToTimeH) + ":"+ String.valueOf(SetTimeActivity.intToTimeM);
SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);
private void compareDates()
{
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
date = parseDate(hour + ":" + minute);
dateCompareOne = parseDate(compareStringOne);
dateCompareTwo = parseDate(compareStringTwo);
if (!(dateCompareOne.before( date ) && dateCompareTwo.after(date))) {
....
I am trying to check if current time falls between the specified time. For that I am converting the specified time into strings first (in Line5 & Line6). Even though I get the integer values correct, the string formed always shows "0:0".
Also, the year is shown as 1970 (The date & the day shown are wrong as well).
I need to get the current time. What am I doing wrong?
private Date parseDate(String date) {
try {
return inputParser.parse(date);
} catch (java.text.ParseException e) {
return new Date(0);
}
}
The parseDate() function returns the time elapsed since the 1st of January 1970. This is known as the Unix Epoch, and it's how all time is represented in Unix computers. By running the parseDate function on a string containing just hours and minutes, you're creating a Date object which represents a time HH:mm past the first of January 1970.
Your code is using a really odd way of getting the current time. Converting a Calendar to two ints, then to a string and finally parsing back to a Date is going to be inefficient and open you up to all sorts of needless errors.
When you initialise a new Date object it is automatically assigned the time of initialisation. Therefore:
Date d = new Date();
would result in d being the moment of initialisation (that is, this year, month, day, hour, minute, second and microsecond). Then you can just use Date.after() and Date.before().
If you still want to do it via the Calendar method, then you'd be better served by:
cal = Calendar.getInstance();
Date d = cal.getTime();
It may be that you've got other issues, but it's worth doing it properly first. When you pass data by writing it as a string (especially when it's time related, with all sorts of ambiguities about what "12" actually represents) you lose all the advantages that language typing gives you.
this code help you
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE); if (c.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (c.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
// Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String formattedDate = df.format(c.getTime());
Toast.makeText(this, formattedDate, Toast.LENGTH_SHORT).show();
If you already work with Date objects why not using the Date.after(...) and Date.before(...) methods.

Compare dates in Android App

I am quite new to Android development, but the person has written the code is away and i have taken over this job.
There is one thing I would like to find out quickly...(--
The app is picking up the user input of a date (using a date picker) and i need add a validation to check the if the date is valid. The valid dates are 30 days from today.
After searching on the internet for long time, i've found a code i might can use:
Date today = new Date();
Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse(today);
if(today.before(predefined)) {
...
}
But I am not sure how to add 30 days?
If you could tell me, that would be much appreciated.
Thanks in advance.
Edit Here is the Source code I've tried.
Calendar today = Calendar.getInstance();
today.add(Calendar.DAY_OF_MONTH,30);
if(calStartDate.compareTo(today)<0) {
Toast.makeText(GetClient.this,"It's before valid date!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(GetClient.this,"It's a valid date!",Toast.LENGTH_SHORT).show();
}
You want the Calendar class. You can create one and set it to current time/date, and create another and set roll it forward 30 days. Then call compareTo() on one passing in the other.
Implement this logic in ur OnDateSetListener:::
class DateListner implements OnDateSetListener
{
#Override
public void onDateSet ( DatePicker view , int year , int monthOfYear ,
int dayOfMonth )
{
Date inputDate = new Date(year, monthOfYear, dayOfMonth);
Long inputTime = inputDate.getTime();
Calendar calendar=Calendar.getInstance();
Date validDate = new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), (calendar.get(Calendar.DAY_OF_MONTH)+30));
Long validTime = validDate.getTime();
if(validTime>inputTime){
Log.e("result", "valid");
}
else
Log.e("result", "invalid");
}
}
Cheers......!!!!

Categories

Resources