Date displaying incorrect in Android - android

I am developing an application in that when time is 11:26 it is showing 11:07. I used Calendar instance to do.
Calendar currentDate=Calendar.getInstance();
SimpleDateFormat ddMMyyyy=new SimpleDateFormat("dd/MM/yyyy");
datenow=ddMMyyyy.format(currentDate.getTime());
if(currentDate.get(Calendar.AM_PM)==Calendar.PM){
timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MONTH)+":PM";
}else{
timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MONTH)+":AM";
}
new MyToast(this, "Date = "+datenow+" time = "+timenow);
The out put is wrong what to do?

you are displaying month in place of minute. Change your code to my code
Calendar currentDate=Calendar.getInstance();
SimpleDateFormat ddMMyyyy=new SimpleDateFormat("dd/MM/yyyy");
String datenow = ddMMyyyy.format(currentDate.getTime());
String timenow;
if(currentDate.get(Calendar.AM_PM)==Calendar.PM){
timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MINUTE)+":PM";
}else{
timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MINUTE)+":AM";
}
Toast.makeText(MainActivity.this, "Date = "+datenow+" time = "+timenow,Toast.LENGTH_SHORT).show();
11:07 is displaying because 07 ==> month number in a year. month will be calculated from 0 -> 11

You have mistaken see here Calendar.HOUR + : + Calendar.MONTH. It should be as follows,
Calendar currentDate=Calendar.getInstance();
SimpleDateFormat ddMMyyyy=new SimpleDateFormat("dd/MM/yyyy");
datenow=ddMMyyyy.format(currentDate.getTime());
if(currentDate.get(Calendar.AM_PM)==Calendar.PM){
timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MINUTE)+":PM";
}else{
timenow=currentDate.get(Calendar.HOUR)+":"+currentDate.get(Calendar.MINUTE)+":AM";
}
new MyToast(this, "Date = "+datenow+" time = "+timenow);
Instead of MINUTE you were accessing MONTH object of Calendar Class.

Related

Compare dates from string without time

I need to compare whether a date is after another date. For example, today is 12 January 2020. First, I tried this:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date pDate = dateFormat.parse("12/01/2020");
Date currentDate = new Date();
if (currentDate.after(pDate)) {
Toast.makeText(getApplicationContext(), "after", Toast.LENGTH_LONG).show();
}
Although both date are the same, I got the toast "after". Then I tried this:
Date currentDate = new Date();
if (currentDate.after(currentDate)) {
Toast.makeText(getApplicationContext(), "after", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "same day", Toast.LENGTH_LONG).show();
}
This time I got the toast "same day". Lastly I changed to date to 13/01/2020:
Date pDate = dateFormat.parse("13/01/2020");
Date currentDate = new Date();
if (currentDate.after(pDate)) {
Toast.makeText(getApplicationContext(), "after", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "before", Toast.LENGTH_LONG).show();
}
And I got the toast "before". The method seems working, but why the first code returned "after" even both date are the same?
Actually your first scenario works as expected. The date that you compare with current date is really before of current date. Let me explain:
pDate contains Sun Jan 12 00:00:00 where time part is 00:00:00
currentDate contains Sun Jan 12 17:05:19 where time part is 17:05:19
So, your currentDate always after of your pDate.
To overcome this you have to compare date part only.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date pDate = dateFormat.parse("12/01/2020");
Date currentDate = dateFormat.parse(dateFormat.format(new Date()));
if (currentDate.after(pDate)) {
Toast.makeText(getApplicationContext(), "after", Toast.LENGTH_LONG).show();
}
you can look at date class source code here, it shows that they use the number of milliseconds for each dates. you are ignoring the hours, minutes and seconds values, and that's why you got the first result
Problem solved by converting the today time to 00:00:00
private Date getZeroTimeDate(Date date) {
Date res;
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
res = calendar.getTime();
return res;
}
Then
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date pDate = dateFormat.parse("12/01/2020");
Date currentDate = new Date();
if (getZeroTimeDate(currentDate).after(pDate)) {
Toast.makeText(getApplicationContext(), "after", Toast.LENGTH_LONG).show();
}

How to set alarm manager using date and time from Textview

I am converting a timestamp into date and time and setting the result on a textview.
For example 1443884578 is Sat 3 October 2015 18:02
I would like to set the above date and time into an alarm manager.After research i found a code that uses a date time picker.
public void onDateSelectedButtonClick(View v) {
// Get the date from our datepicker
int day = picker.getDayOfMonth();
int month = picker.getMonth();
int year = picker.getYear();
// Create a new calendar set to the date chosen
// we set the time to midnight (i.e. the first minute of that day)
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
// Ask our service to set an alarm for that date, this activity talks to the client that talks to the service
scheduleClient.setAlarmForNotification(c);
// Notify the user what they just did
Toast.makeText(this, "Notification set for: " + day + "/" + (month + 1) + "/" + year, Toast.LENGTH_SHORT).show();
}
However its getting only the date and fires the alarm the minute the date occurs.
PROBLEM: I would like to get the date and time from my textview and skip this date time picker in the format i have. Is this possible?
String input = "Sat October 3 2015 18:02"; // Instead of String input = "Mon Feb 06 2015";
Calendar cal = Calendar.getInstance();
Date date = new Date();
// Changed the format to represent time of day
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.ENGLISH);
try {
date = sdf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
cal.setTime(date);
//We haven't parsed the seconds from the original date so this will result
//in 18:02:00 - 10seconds.
//For a correct calculation, you could parse the seconds as well
//See SimpleDateFormat above, but you would have to provide the original date
//with seconds as well
cal.add(Calendar.SECOND, -10);
scheduleClient.setAlarmForNotification(cal);

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.

How to get First Day and last day of the week of a date

I am using DatePickerDialog to show the calender. I want to access First day and last day of the week of the date selected.
Here is what I have tried
this.tv_date.setText( new StringBuilder()
// Month is 0 based so add 1
.append(mDay).append("-")
.append(monthName).append("-")
.append(mYear).append(""));
tv_date.setHighlightColor(Color.CYAN);
String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
sdf.format(""+str); //here I am getting exception
Calendar cal=Calendar.getInstance();
int s= cal.getFirstDayOfWeek();
Toast.makeText(getApplicationContext(), "first day of the week : "+s, 1).show();
But I am getting "IllegalArguementException".
Please help me
Thanks
sdf.format(""+str); - is wrong. You either need to pass a Date object to it, or else, change it to sdf.parse(str); to get a Date object from it.
Edit:- To get the first day of the week, do this.
String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
Date myDate = new Date();
try{
myDate = sdf.parse(str);
}catch(ParseException pe){
// Do Something
}
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
cal.set(Calendar.DAY_OF_WEEK, 1);
int s = cal.get(Calendar.DATE);
Here is an example of calculating the first day of week.
private void firstDayOfThisWeek(){
DateTime today = DateTime.today(TimeZone.getDefault());
DateTime firstDayThisWeek = today; //start value
int todaysWeekday = today.getWeekDay();
int SUNDAY = 1;
if(todaysWeekday > SUNDAY){
int numDaysFromSunday = todaysWeekday - SUNDAY;
firstDayThisWeek = today.minusDays(numDaysFromSunday);
}
System.out.println("The first day of this week is : " + firstDayThisWeek);
}
Instead of assigning today you can assign any other day with exact format

How to get day from specified date in android

Suppose my date is 02-01-2013
and it is stored in a variable like:
String strDate = "02-01-2013";
then how should I get the day of this date (i.e TUESDAY)?
Use Calendar class from java api.
Calendar calendar = new GregorianCalendar(2008, 01, 01); // Note that Month value is 0-based. e.g., 0 for January.
int reslut = calendar.get(Calendar.DAY_OF_WEEK);
switch (result) {
case Calendar.MONDAY:
System.out.println("It's Monday !");
break;
}
You could also use SimpleDateFormater and Date for parsing dates
Date date = new Date();
SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd");
try {
date = date_format.parse("2008-01-01");
} catch (ParseException e) {
e.printStackTrace();
}
calendar.setTime(date);
First split the string
String[] out = strDate.split("-");
s1 = Integer.parseInt(out[0]);
s2 = Integer.parseInt(out[1]) - 1;
yr = out[2];
char a, b, c, d;
a = yr.charAt(0);
b = yr.charAt(1);
c = yr.charAt(2);
d = yr.charAt(3);
s3 = Character.getNumericValue(a)*1000 +
Character.getNumericValue(b)*100 +
Character.getNumericValue(c)*10 +
Character.getNumericValue(d);
then create a calendar instance on that day
Calendar cal = Calendar.getInstance();
cal.set(s3, s2, s1);
then get the day
cal.get(Calendar.DAY_OF_WEEK);
use this format for date, day and time.
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
and get out put of object here with format method.
ft.format(dNow)
I think that based on Android documentation is suggested the use of Calendar,
You need to be careful because the first day 1 is Sunday and the first month January
Also check that you can get DAY_OF_WEEK, DAY_OF_MONTH etc

Categories

Resources