Time format bug for 12 AM/PM in android - android

Im creating an alarm apps for android. I dont really understand about time format so i go googling and got this post.
I followed that post, but a bug still remains : My apps cant tell the difference between (lets say) 12:17 AM and 12:17 PM. So the bug will occurred if the hour is 12.
What i did when taking the value form the TimePicker (hh:m:aa) format :
String hour = "";
Calendar datetime = Calendar.getInstance();
datetime.set(Calendar.HOUR_OF_DAY, timeSchedule.getCurrentHour());
datetime.set(Calendar.MINUTE, timeSchedule.getCurrentMinute());
if (datetime.get(Calendar.AM_PM) == Calendar.AM && timeSchedule.getCurrentHour() == 0) //12 AM = 0
hour = "00"+ ":" + timeSchedule.getCurrentMinute();
else
hour = timeSchedule.getCurrentHour() + ":" + timeSchedule.getCurrentMinute();
With above code, 12:17 AM will become 00:17 while 12:17PM will become 12:17PM. This value is stored in the mysql Time format. Since i want to create an alarm apps, please kindly tell me whether i did is right or not.
And this is what i did to show them to the user, where 00:17 (taken from the result of above code) become 12:17AM (correct) but 12:17 become 12:17AM (wrong) :
String time = getItem(position).getTime(); //value from above code
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
SimpleDateFormat newFormat = new SimpleDateFormat("hh:mm:aa");
String formatedTime = "";
try {
Date date = format.parse(time);
formatedTime = newFormat.format(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
To be honest, this is the first time i deal with somekind of alarm app, so please kindly tell me if i do something wrong. (beside my bug)
Thanks for your time.
UPDATE
This is what i did now :
I changed the mysql column from Time to Varchar, because Time wont let me insert "AM/PM".
After that :
String hour = "";
Calendar datetime = Calendar.getInstance();
datetime.set(Calendar.HOUR_OF_DAY, timeSchedule.getCurrentHour());
datetime.set(Calendar.MINUTE, timeSchedule.getCurrentMinute());
String am_pm = "";
if (datetime.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else
am_pm = "PM";
hour = (datetime.get(Calendar.HOUR) == 0) ?"12":datetime.get(Calendar.HOUR)+"";
final String time = hour+ ":" + datetime.get(Calendar.MINUTE) + " " + am_pm ;
Above code return 12:17 AM and 12:17 PM. With this, i dont have to use SimpleDateFormat to re-format the date again. Is this the correct way to set the time for alarm?

I am a bit confused with the notation you want to use. There are two approaches for representing AM, PM hours. Either in the range of 0:00-11:59 or in the range 1:00-12:59. You do not use either, thus you get troubles in representing the hours you encounter. PLease read through the different options provided in SimpleDateFormat.
Also restrain from using your own conversition - use the sdk class everywhere, thus you will ensure you do not get into made up format.

Related

How do I get the time an hour from now for my 12 hour time format in string?

I am planning to add an hour to the current time, which I have converted into a 12 hour format. Just not sure how to go about it. I want to keep mins the same, just want to add an hour, say the time is 11:59am -> I would like to show 12:59pm, or if the time is 5:20, I would like to show 6:20 and so on.
Here's my code so far :
if (mDate.get(Calendar.AM_PM) == Calendar.AM)
am_pm = "AM";
else if (mDate.get(Calendar.AM_PM) == Calendar.PM)
am_pm = "PM";
String strHrsToShow = (mDate.get(Calendar.HOUR) == 0) ? "12" : mDate.get(Calendar.HOUR) + "";
String strMinsToShow = (mDate.get(Calendar.MINUTE)) < 10 ? "0" + mDate.get(Calendar.MINUTE) : "" + mDate.get(Calendar.MINUTE);
mRegisterGuestStartTime.setText(String.format("%s:%s %s", strHrsToShow, strMinsToShow, am_pm));
Any ideas how to go about it? thanks in advance!
mDate is a Calendar object I assume. If yes, why don't you use Calendar.add(Calendar.HOUR, 1)? Doing it in String manipulation way lost the precision of the date/time value. You can use SimpleDateFormat to format the Calendar afterward
// add an hour to the date
mDate.add(Calendar.HOUR, 1);
// prepare datetime formatter, sample output: "11:35 AM"
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm a");
mRegisterGuestStartTime.setText(timeFormat.format(mDate.getTime()));

Same Milliseconds values coming for different dates

I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.

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.

Determining if a time is between two other times

I am trying to take hours that I've parsed using SimpleDateFormat and determining whether or not the current time is between the two sets of hours. Basically, given a place's hours, I'm trying to determine if it is currently open our closed.
I am getting the current time by doing the following:
SimpleDateFormat sdf2 = new SimpleDateFormat("kk:mm");
Calendar now = Calendar.getInstance();
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
String currentHour = Integer.toString(hour);
String currentMinute = Integer.toString(minute);
String timeNow = currentHour + ":" + currentMinute;
Date timeRightNow = sdf2.parse(timeNow);
Then, I determine whether timeRightNow is between the opening and closing times, I am doing the following:
if (timeOpen.before(timeRightNow) && timeClose.after(timeRightNow)) {
openStatus = "open!";
} else {
openStatus = "closed.";
}
Both timeOpen and timeClose are found by parsing a String using sdf2 in the exact same way as timeRightNow is found.
Every time that this runs, it sets openStatus to "closed." even when the current time is between the open and close times. Can anyone point me in the right direction to figure out why this is happening?
I changed Calendar.HOUR to Calendar.HOUR_OF_DAY. This resolved the issue.

How to fetch current GMT value?

In my app, I am using GeoNamesAPI for fetching the current time at any location.
I have registered for using that.
My code looks like:
Timezone currentTimeZone;
org.geonames.WebService.setUserName("mathew");
currentTimeZone = GeoNamesAPI.fetchTimeZone(latitude, longitude);
The problem is when I check time at any ocean, this currentTimeZone returns null.
So in that case, I show the GMT value.
String time = null;
Integer timeZone = (int) (((longitude / 7.5) + 1) / 2);
if (timeZone >= 0) {
time = "GMT+" + timeZone;
} else {
time = "GMT" + timeZone;
}
So the time value will be of the kind GMT+somevalue. I want to find another solution for this case. In this case also I want to display the time value. How can I do that? Is there any way to get the GMT value? Note: I dont want to show the date only time is required.
Thanks in advance.
I got it worked. Code is given below:
Integer timeZone = (int) (((longitude / 7.5) + 1) / 2);
DateFormat dateformat = DateFormat.getTimeInstance(DateFormat.SHORT);
dateformat.setTimeZone(TimeZone.getTimeZone("gmt"));
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, timeZone); //Adding/Subtracting hour to current date time
String newdate = dateformat.format(cal.getTime());

Categories

Resources