I know am not the first to ask this ,What I need to do is when I close the current activity by clicking on a button ,I want to show the current time .
This will have the following validation.
1,In the current activity I have a timepicker if I select any time any click on the save button it will show the sellected time and closing the current activity.
2,If I am not selected any time from timepicker and On the save button click I want to show the current time .
For me the First one is working fine but the second one is always showing null.
TimePicker Time :
mTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
#Override
public void onTimeChanged(TimePicker timePicker, int i, int i1) {
int hour = i % 12;
mselectedTime = (String.format("%02d:%02d %s", hour == 0 ? 12 : hour, i1, i < 12 ? "AM" : "PM"));
}
});
code :
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mselectedTime == "null"){
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm.ss aa");
Toast.makeText(getApplicationContext(),"Time Is :" + dateFormat, Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(), mselectedTime, Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(CreateAlarm.this, AlarmActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_out, R.anim.slide_out);
}
});
Here the second Toast is showing the time ,but First toast is always showing empty .I need to show the time as 04:50 Am/Pm format in the first toast
Can anyone tell me where I did the mistake .
In the second toast you need to reacquire the time, then add it to the toast, not the SimpleDateFormat. Here's the code:
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh.mm.ss aa");
String output = dateFormat.format(currentTime);
Toast.makeText(getApplicationContext(),"Time Is :" + output, Toast.LENGTH_LONG).show();
Using Calendar instance you can get current hour and minutes
Calendar c;
private int mhour;
private int mminute;
c = Calendar.getInstance();
mhour = c.get(Calendar.HOUR);
mminute = c.get(Calendar.MINUTE);
// you will get current hour and minutes of device time
also refer to this
DateFormat dateFormat = new SimpleDateFormat("hh.mm aa");
String dateString = dateFormat.format(new Date()).toString();
Toast.makeText(this,"Current time :"+ dateString,Toast.LENGTH_LONG).show();
and you may have imported wrong packages use.
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
Related
I am developing an application in which there is a scenario that whatever the time I chose, the next part is to subtract 1 minute from the time string and add the new time in minutes to the List.
For example, this is my code till now:
viewHolder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Date date = (Date) mtablayoutCourtDetailsAvailability.getTabAt(mtablayoutCourtDetailsAvailability.getSelectedTabPosition()).getTag();
String key = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).format(date);
List<String> stringList = stringListMap.get(key);
if (isChecked)
{
stringList.add(buttonView.getText().toString());
}
else
{
stringList.remove(buttonView.getText().toString());
}
stringListMap.put(key, stringList);
}
});
Now in this code, the line below refers to the time that the user will select
buttonView.getText().toString()
time slots are available like that: "09:00 AM - 10:00 AM"
so whenever any slot is checked there will be some time slot text in buttonView that will be added to list. However, I want to subtract 1 minute from the time that is after "-" i.e. if user select "09:00 AM - 10:00 AM" then the new time that will add in the stringList must be "09:00 AM - 09:59 AM".
Unfortunately, I am unable to achieve this as I am new to this thing. I am able to achieve the second time slot value after "-" with the following code
String[] namesList = buttonView.getText().toString().split("-");
String partbefore= namesList[0];
String partafter= namesList[1];
partafter will contain 10:00 AM which I should change to 09:59 AM after subtracting 1 minute from this. How can I achieve this? Please Help
Use this code to get. set original time as your requirement,
try {
String original_time = "2018-11-11 11:02 am", time_required;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm");
Date date;
Calendar cal = Calendar.getInstance();
date = dateFormat.parse(original_time);
time_required = localDateFormat.format(date);
cal.setTime(date);
cal.add(Calendar.MINUTE, -1);
time_required = localDateFormat.format(cal.getTime());
} catch (Exception ex) {
Toast.makeText(this, ""+ex.getMessage(), Toast.LENGTH_SHORT).show();
}
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.
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.
I have a textview which shows the day of the week as an integer (0-7). I would prefer if it could convert that to a string, which could then be shown in a TextView. My code is below. Also, how can I make it so the TextViews update the time, date, etc. (it only shows the time the app is opened)? Thanks in advance.
MainActivity.java:
package press.linx.calendar;
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.os.Bundle;
import android.app.Activity;
import android.text.format.Time;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView day = (TextView)findViewById(R.id.day);
TextView month = (TextView)findViewById(R.id.month);
TextView year = (TextView)findViewById(R.id.year);
TextView time = (TextView)findViewById(R.id.time);
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
day.setText("" + today.monthDay); // Day of the month (0-31)
month.setText("" + today.month); // Month (0-11)
year.setText("" + today.year); // Year
time.setText("" + today.format("%k:%M")); // Current time
}
}
UPDATE: I got it using this piece of code:
final Calendar calendar = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("MMM"); // 3-letter month name & 2-char day of month
TextView datetxt = (TextView) findViewById(R.id.nameofyourtextview);
datetxt.setText(formatter.format(calendar.getTime()));
To format your Time:
Time time = new Time();
time.format("%A");
It returns name of day in week (Sunday, Friday..) - see description of format string (It's a PHP man page, but the symbols are same and it's well-aranged)
In order to make textViews updated every second you have to use Timer and TimerTask.
Define UpdateTimeTask:
class UpdateTimeTask extends TimerTask {
public void run() {
// Update time, must be called using runOnUiThread
}
}
and then set timer:
Timer timer = new Timer();
TimerTask updateTime = new UpdateTimeTask();
timer.scheduleAtFixedRate(updateTime, 0, 1000);
I assume you are looking for the date to be displayed in the below format.
You can use the below
Date now = new Date();
SimpleDateFormat dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
System.out.println("Format : " + dateFormatter.format(now));
Output
Format : Thursday, April 25, 2013
Few helpful links
http://www.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html
http://www.roseindia.net/tutorial/java/core/convertDateToWords.html
To get the current day of the week (i.e. Monday, Tuesday, Wednesday, etc.) try:
DateFormat fmt = new SimpleDateFormat( "EEEE" );
fmt.format( new java.util.Date() );
Try this
month.setText(getMonth(today.month));
day.setText(getWeek(today.monthDay));
method to get month based on month number
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month];
}
method to get week based on week number
public String getWeek(int weekno) {
return new DateFormatSymbols().getWeekdays()[weekno];
}
Do you mean display as Mon, Tue, Wed,.... ?
Use this format.
SimpleDateFormat curFormatDate = new SimpleDateFormat("EEE");