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();
}
Related
I'm using Parse as a data store for an app I'm building. I have a Date parameter within the class that stores the expiry date of a food that is saved to Parse. The date is inputted using a datepicker (code below)
The date picker is created as such:
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
expiry_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DatePickerDialog(AddItem.this, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
});
And the update label method converts it to a readable date and displayed in an EditText
private void updateLabel() {
String myFormat = "dd/MM/yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);
EditText update = (EditText) findViewById(R.id.expiry_date);
update.setText(sdf.format(myCalendar.getTime()));
}
Then, when the date is saved, it converts in from a string to a date
String dateString = expiry_date.getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(dateString);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
This displays the correct date, as I'd expect. When saved however, the date is incorrect. For example, if I chose 28/08/2015, it would be saved in the Parse core as 27/08/2015:2300. It always saves as the day before with 11pm appended to it.
I wouldn't mind a time being appended to the date, but I'd prefer it to be 11:59pm on the day I picked, so I can compare dates later.
When the dates are displayed, they actually display the correct date (as in, the one picked from the date picker), rather than the saved date in Parse.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String date = sdf.format(Calendar.getInstance().getTime());
Date datecomp = new Date();
datecomp.getDate();
int check = object.getDate("expiry").compareTo(datecomp);
Format formatter = new SimpleDateFormat("dd/MM/yyyy");
I'm assuming this is something to do with the date conversion, but I can't figure out why it's doing this, and I've looked at a lot of different sources, but none seem to describe my problem. Any help would be much appreciated
Parse stores dates as GMT reference (not +3h or -2h GMT e.i someone from Turkey and someone from US have different time at the same moment.) So you should make localization on your application via keeping client timezone in parse db.
int offsetInMs = 3600000;
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
TimeZone timeZone = calendar.getTimeZone();
TimeZone gmt0 = timeZone.getTimeZone("GMT0");
TimeZone gmtNewYork = timeZone.getTimeZone("America/New_York");
TimeZone gmtLondon = timeZone.getTimeZone("Europe/London");
TimeZone gmtIstanbul = timeZone.getTimeZone("Asia/Istanbul");
TimeZone local = timeZone.getDefault();
System.out.println(gmt0.getID()+" -> "+gmt0.getOffset(date.getTime())/offsetInMs);
System.out.println(gmtNewYork.getID() + " -> " + gmtNewYork.getOffset(date.getTime())/offsetInMs);
System.out.println(gmtLondon.getID() + " -> " + gmtLondon.getOffset(date.getTime())/offsetInMs);
System.out.println(gmtIstanbul.getID() + " -> " + gmtIstanbul.getOffset(date.getTime())/offsetInMs);
System.out.println(local.getID()+ " -> " + local.getOffset(date.getTime())/offsetInMs);
i.e. Your local time zone is GMT+2 and local time is 15:00,
Parse save it as 13:00(GMT). You shoud create a column named GMTOffset which keeps GMT+2.
Results:
GMT0 -> 0, America/New_York -> -4, Europe/London -> 1, Asia/Istanbul -> 3, Asia/Istanbul -> 3
I think that Parse basetime is GMT0. Create a column named GMTOffset which keeps -4, 1, 3, 3 (user local offset).
Additionally, if you will use parse time in your application, Parse may localize time on the client side. Please check that also.
P.S. as my experience, client side time is not reliable, you should use your server(if exist) time.
Can you help on adding time using calendar method? In my layout I have a clock and sorrounds by numbers each number are setOnTouchListener. What I want to do is this if user tap on each number it will add 10 hours. e.g When user touch on number 1 so the time would become 11.
If there's other way please show it to me how.Thanks
Here's my activity code
String timeOut = "2:00";//set the time
int time1 = Integer.parseInt(timeOut); //converting the string into integer
Calendar cld = cld.getInstance();
cld.add(Calendar.HOUR, 10); //in this line here I want to add the variable time1
tetxtView.setText("You added time is equal to " + cld.getTime());
from what you are saying, I understand that the user clicked on 2 so, you need to display 12.
so just add 10 + time1 = 10+2 = 12.
String timeOut = "2:00";//set the time
int time1 = Integer.parseInt(timeOut);
Calendar cld = cld.getInstance();
cld.add(Calendar.HOUR, 10 + time1); //in this line here I want to add the variable time1
now you will see , 12 as your time.
let me know if this solves your prob..
Try this:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = null;
try {
date = sdf.parse("12:22");
System.out.println("Date "+date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, 10);
System.out.println("Calendar hour "+ sdf.format(calendar.getTime())); //Just format it as i have added this line
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.
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 am trying to convert a string that contains a time stamp to a time that is consistent with androids RelativeDateTimeString, so I can format it as a relative time. The time stamps that I get are in this format:
2011-08-17 04:57:38
I would like to take that string and pass it through my relative time function here:
public void RelativeTime(Long time){
String str = (String) DateUtils.getRelativeDateTimeString(
this, // Suppose you are in an activity or other Context subclass
time, // The time to display
DateUtils.SECOND_IN_MILLIS, // The resolution. This will display only minutes
// (no "3 seconds ago"
DateUtils.WEEK_IN_MILLIS, // The maximum resolution at which the time will switch
// to default date instead of spans. This will not
// display "3 weeks ago" but a full date instead
0); // Eventual flags
toast(str);
}
So the function should show a toast of "2 days ago" etc.
EDIT: Sorry I have a toast function I've written as well.
public void toast(String text){
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
Use SimpleDateFormat and it's parse() function to convert your timestamp from a string to a Date object. After that you can use Date.getTime() to get the long value of your timestamp in ms.
Please check the below code i have modified it, may this solve your problem:
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US);
Date now = formatter.parse("2014-01-26 05:36:38 PM");
Calendar calendar=Calendar.getInstance(Locale.US);
calendar.setTime(now);
RelativeTime(now.getTime());
} catch (Exception e) {
e.printStackTrace();
}
public void RelativeTime(Long time){
String str = (String) DateUtils.getRelativeDateTimeString(
this, // Suppose you are in an activity or other Context subclass
time, // The time to display
DateUtils.SECOND_IN_MILLIS, // The resolution. This will display only minutes
// (no "3 seconds ago"
DateUtils.WEEK_IN_MILLIS, // The maximum resolution at which the time will switch
// to default date instead of spans. This will not
// display "3 weeks ago" but a full date instead
0); // Eventual flags
toast(str);
}
public void toast(String text){
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
i believe the way you are calling toast is incorrect.
Try this link it should help you out a little more.
Toasty Bread. i just gave that a crazy name lol
You need SimpleDateFormat
Something like the following code may help you
"format" is the coding stucture of your string date like "dd MMM yyyy hh:mm:ss zzz"
"Value" in the code is your string date.
See http://developer.android.com/reference/java/text/SimpleDateFormat.html to have details on format and other "methods" about SimpleDateFormat
SimpleDateFormat sf = new SimpleDateFormat(format);
sf.setTimeZone(TimeZone.getTimeZone("UTC"));
//sf.setCalendar(Calendar.getInstance());
ParsePosition pp = new ParsePosition(0);
Date date = sf.parse(Value,pp);
if (pp.getIndex() == 0) {
Log.e(TAG,"Can't getDate with format:\""+format+"\" and value:\""+Value + "\" at char index:"+pp.getErrorIndex());
return Calendar.getInstance();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.getTimeInMillis(); is compatible with your "time" parameter (long type)