I want to display a message in a textview, the code that i use right now is
mText = (TextView) findViewById(R.id.textView19);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String str = sdf.format(new Date());
String[] hr=str.split(":");
int hr1=Integer.parseInt(hr[0]);
if(hr1<12)
{
mText.setText("it's morning!");
}else if(hr1>12&& hr1<17)
{
mText.setText("it's afternoon!");
}else if(hr1>17&& hr1<20)
{
mText.setText("it's evening!");
}
But that code doesnt work at all it doesnt type anything in the textview.
How do i fix this?
You are creating a null date, you need to get the current time by doing:
Calendar c = Calendar.getInstance(); // Get current time
int hr1 = c.get(Calendar.HOUR_OF_DAY); // Gets the current hour of the day from the calendar created ( from 1 to 24 )
Check the Calendar documentation here.
Related
I have a start date = "13:45"
and an end date = "14:35"
Now i would like to check if the system time is between these two times, for example "14:00"
I have tried the methods before and after from the Date class but it did not worked properly
Any Suggestions ?
SimpleDateFormat format = new SimpleDateFormat("HHmm",
Locale.getDefault());
String now = format.format(new Date());
String start = "13:45".replace(":", "");
String end = "14:35".replace(":", "");
boolean isBetween = Integer.valueOf(now) > Integer.valueOf(start)
&& Integer.valueOf(now) < Integer.valueOf(end);
System.out.println(isBetween);
Maybe you could do something like this:
Calendar start = Calendar.getInstance();
start.set(Calendar.HOUR_OF_DAY, 13);
start.set(Calendar.MINUTE, 45);
Calendar current = Calendar.getInstance();
Calendar end = Calendar.getInstance();
end.set(Calendar.HOUR_OF_DAY, 14);
end.set(Calendar.MINUTE, 35);
if(current.after(start) && current.before(end)){
//we are between
}
I have a custom dialog with a datepicker and a time picker in it. The user sets the Date which all works fine. The date picker is the hidden and the time picker is shown. I am currently setting the time on the timepicker manually to 8 am.
I now want to convert the user set time in the time picker to a long which I am able to do however its showing me the current time on the phone in the logcat and not the actual set time... Thanks!
button_continue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (timeset == false) {
Calendar calendar = Calendar.getInstance();
calendar.set(datePickerDiet.getYear(), datePickerDiet.getMonth(), datePickerDiet.getDayOfMonth());
long startTime = calendar.getTimeInMillis();
System.out.println(startTime);
// save to shared pref
ProfilePrerences.getInstance().setLongValue(DietActivity.this, ProfilePrerences.KEY_START_DIET_DAY, startTime);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(startTime));
System.out.println(dateString);
datePickerDiet.setVisibility(View.GONE);
time_breakfast.setVisibility(View.VISIBLE);
dialog_txt.setText("At what time do you have breakfast?");
time_breakfast.setCurrentHour(8);
time_breakfast.setCurrentMinute(0);
time_breakfast.clearFocus();
timeset = true;
}
else if (timeset == true) {
// time_breakfast.setVisibility(View.VISIBLE);
Calendar calendar2 = Calendar.getInstance();
calendar2.set(time_breakfast.getCurrentHour(), time_breakfast.getCurrentMinute(), 0);
long breakfasttime = calendar2.getTimeInMillis();
System.out.println(breakfasttime);
SimpleDateFormat formatter2 = new SimpleDateFormat("hh:mm");
String dateString2 = formatter2.format(new Date(breakfasttime));
System.out.println(dateString2);
// startdietdialog.cancel();
ProfilePrerences.getInstance().setLongValue(DietActivity.this, ProfilePrerences.KEY_BREAKFAST_TIME, breakfasttime);
timeset = false;
}
}
});
This line is causing you the problem:
calendar2.set(time_breakfast.getCurrentHour(), time_breakfast.getCurrentMinute(), 0);
This is setting the year, month, day on calendar2 - not the hour, minute, second you intended.
Probably the easiest solution is call the direct methods - setHour, setMinute, etc., on calendar2.
Two things: you're printing the current date (new Date):
String dateString2 = formatter2.format(new Date(breakfasttime));
System.out.println(dateString2);
You have to print calendar2 time:
String dateString2 = formatter2.format(calendar2.getTime());
System.out.println(dateString2);
The other is, Greg Ennis said, you're setting calendar2 time incorrectly: there is not such method to set only the hour, minutes and seconds. You should set year, month and day also or call set(Calendar.HOUR, h), set(Calendar.MINUTE, m), etc separately
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.
Can any one tell me how to set the current time in edittext box in android with out using Time-picker.
edt_time=(EditText) findViewById(R.id.editText_time);
Time t = new Time();
java.text.Time tf = android.text.format.Time.getCurrentTimezone(getApplicationContext());
edt_time.setText(tf.format(t));
Suggestions please.
Thanks for your precious time!..
Calendar c = Calendar.getInstance();
int mHour = c.get(Calendar.HOUR);
int mMinute = c.get(Calendar.MINUTE);
int mSeconds = c.get(Calendar.SECONDS);
EditText edt_time=(EditText) findViewById(R.id.editText_time);
edt_time.setText(mHour +":"+ mMinute +:+ mSeconds);
Similarly you can also get year, month,day etc.
The above code must work but anyway try this.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String currentTime = sdf.format(new Date());
EditText edt_time=(EditText) findViewById(R.id.editText_time);
edt_time.setText(currentTime);
long time = System.currentTimeMillis(); // current time in miliseconds, conver it however you want
then put in editText,
editText.setText(String.valueOf(time));
Been confusing.. Like if we are comparing time, string is definitely not recommended... But if it is in the format of (HH:mm:ss). how should i compare them to do something?
For example:
Target1: 9:00:00
Target2: 23:00:00
how to do the logic for comparison where the input is larger than Target1 and smaller than Target2?
if(input > Target1 && input < Target2){
//do statement A
}else{
//do statement B
}
so if my input time is 10:00:00, it should run statement A
and if input time is 23:01:00, it should run statement B
how should i do that? is larger than (>) and smaller than (<) appropriate in time format?
Given them as string, you can convert them to a Date object from a SimpleDateFormat.
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
The easiest way is to convert them to the amount of milliseconds by doing
long time1 = sdf.parse(Target1).getTime();
long time2 = sdf.parse(Target2).getTime();
long inputTime = sdf.parse(input).getTime();
This way you are essentially doing a integer comparison, and you can forget about all the Date Time business.
if(inputTime > time1 && inputTime < time2)
SimpleDateFormat df=new SimpleDateFormat("hh:mm:ss");
Date d1=df.parse(dateToPars);
d1.after(otherTimeYouWantTocompare); OR
d1.before(otherTimeYouWantTocompare);
But you have to provide the time in the mentioned format
you can calculate diffrent using calender function .getTimeInMillis(), and get diffrent of 2 diffrent time , here you need to set only your specific time in Calender and make comparision with it
try{
Calendar calender = Calendar.getInstance();
Calendar calDb = Calendar.getInstance();
Calendar matchd = Calendar.getInstance();
mYear = calender.get(Calendar.YEAR);
mMonth = calender.get(Calendar.MONTH);
mDay = calender.get(Calendar.DAY_OF_MONTH);
mendYear = calDb.get(Calendar.YEAR);
mendMonth = calDb.get(Calendar.MONTH);
mendDay = calDb.get(Calendar.DAY_OF_MONTH);
// Here you can change day values
calDb.set(Calendar.DAY_OF_MONTH, mDay-1);
strbeforedate = mDateFormat.format(calDb.getTime());
curentdate = mDateFormat.format(calender.getTime());
calDb.setTime(mDateFormat.parse(strbeforedate));
calender.setTime(mDateFormat.parse(curentdate));
String mydate = "2013.03.14 03:11";
String mdatetime = "";
deletepath = new ArrayList<String>();
try{
// here your matching goes and pass date here
matchd.setTime(mDateFormat.parse(mdatetime));
long diff = calDb.getTimeInMillis() - calender.getTimeInMillis();
long matchdiff = matchd.getTimeInMillis() - calender.getTimeInMillis();
if(diff < matchdiff){
// do your work here
}else{
// do your else work here
}
}catch(Exception e){
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}