Android, SimpleDateFormat not working - android

I'm trying to parse time only but the app code includes the date and the year.
here is my code:
simpleDateFormat2 = new SimpleDateFormat("HH:mm");
int h = Integer.parseInt(traffic.alarmClocks.get(0).get(ApplicationConstants.HOUR));
int m = Integer.parseInt(traffic.alarmClocks.get(0).get(ApplicationConstants.MINUTE));
String datex2 = h + ":" + m;
Date storedalarm = simpleDateFormat2.parse(datex2);
output of the datex2 is : 4:56
Output of StoredAlarm is this: http://imgur.com/a/UVpbh
The output of the datex2 is correct, but I need to make it into date because I am going to use it to compare times.

you just need to compare times you could very easily combine hours and minutes this way:
int time = hours * 60 + minutes;
then you could just compare 2 integers.
or if you really want a Date object, you could initialize it with year, month and date to 0, and just pass hours and minutes
Date storedalarm = new Date(0, 0, 0, h, m);
in order to show just hours and minutes from your Date object you can use the same SimpleDateFormat you instantiated before
String formattedDate = simpleDateFormat2.format(storedalarm);

Related

Get a random time between two time

Time 1 : 10:30 06/05/2018
Time 2 : 19:45 06/05 2018
I want to pick a random time between these two time. The result may be (13:15 06/05/2018).
I look into Calendar but seem it does not support a method like range(time1, time2)
What is the solution for this case ? Thanks.
I would use something like this.
public static Calendar getRandomTime(Calendar begin, Calendar end){
Random rnd = new Random();
long min = begin.getTimeInMillis();
long max = end.getTimeInMillis();
long randomNum = min + rnd.nextLong()%(max - min + 1);
Calendar res = Calendar.getInstance();
res.setTimeInMillis(randomNum);
return res;
}
if you have API 21+, use ThreadLocalRandom
public static Calendar getRandomTime(Calendar begin, Calendar end){
long randomNum = ThreadLocalRandom.current().nextLong(begin.getTimeInMillis(), end.getTimeInMillis() + 1);
Calendar res = Calendar.getInstance();
res.setTimeInMillis(randomNum);
return res;
}
you should convert your times objects to long first as follows (I suppose that you have two Calendar objects already)
long time1InLong = time1.getTimeInMillis();
long time2InLong = time2.getTimeInMillis();
Then you can use following code to generate random number
Random r = new Random();
long randomTime = r.nextLong(time2InLong - time1InLong) + time1InLong;
Then you can convert this randomTime back to Calendar as follows
// Create a DateFormatter object for displaying date in specified format.
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm dd/MM/yyyy");
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(randomTime);

Changing Textview Dynamicly after a certain period of Days

I'm quite new to Android and I want to change (I know how to set it dynamically but....)Textview Dynamically after a certain period of Days,but int the meantime keep the text posted unless changed by user or if a certain days have been reached by my program.
Well Basically I have the user to input a Date then i want my program to count days and as long as the user nor my program have intervene with the textview it will show the same text and backround color until the opposite is taken action.
here is my code:
String CurrentDate = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
String FinalDate = TvDateOfService.getText().toString();
SimpleDateFormat dates = new SimpleDateFormat("dd/MM/yyyy");
Date dateinput;
Date datetwra;
//Setting dates
try {
dateinput = dates.parse(FinalDate);
datetwra = dates.parse(CurrentDate);
//Comparing dates
long difference = Math.abs(dateinput.getTime() - datetwra.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
//Calendar Instance to Add 89 Days for Service Period Between Dates!!
Calendar cal1 = Calendar.getInstance();
cal1.add(Calendar.DATE, 90);
Date ServicePeriod = cal1.getTime();
Calendar cal2 = Calendar.getInstance();
cal2.add(Calendar.DATE, 80);
Date DaysBeforeEnd = cal2.getTime();
do {
tvStatus.setBackground(getApplicationContext().getResources().getDrawable(R.drawable.textview_backround_green));
}while (dateinput.before(DaysBeforeEnd));
do {
tvStatus.setText("something");
tvStatus.setBackground(getApplicationContext().getResources().getDrawable(R.drawable.textview_backround_yellow));
}while (dateinput.after(DaysBeforeEnd));
do {
tvStatus.setText("something else");
tvStatus.setBackground(getApplicationContext().getResources().getDrawable(R.drawable.textview_backround_red));
}while (dateinput.after(ServicePeriod));
It looks like you're trying to use a for loop and wait a certain number of days - it would be most beneficial to the phone's battery if you used AlarmManager
https://developer.android.com/trai.../scheduling/alarms.html

convert a string date and time in miliseconds

I want to set alarm .but my date and time are stored in db.when i will get these they are in string. when i will get date and time and it looks like this:
10:33 AM4/11/2015
Please tell me how I can convert this in milliseconds.and I am new here please ignore the problems in question posting.
for (int i = 0; i < names.size(); i++) {
ShoppingListItem item = new ShoppingListItem();
item.setCategory(names.get(i).getCategory());
item.setTitleName(names.get(i).getTitle());
item.setTimeVal(names.get(i).getTime());
item.setCalender(names.get(i).getCalendar());
item.setAddres(names.get(i).getAddress());
item.setDb_row_id(names.get(i).getDb_row_id());
//item.setColorImage(names);
mAdapter.addItem(item);
String s = names.get(i).getTime() + names.get(i).getCalendar();
System.out.println("GetTime"+s);
You need to parse the formatted string date. Try this:
SimpleDateFormat sdformat = new SimpleDateFormat("hh:mm aaMM/dd/yyyy");
Date date = sdformat.parse(your-string-date);
long milliseconds = date.getTime(); //<--here gets the milliseconds
Please try the following code
Calendar rightNow = Calendar.getInstance();
// offset to add since we're not UTC
long offset = rightNow.get(Calendar.ZONE_OFFSET) +
rightNow.get(Calendar.DST_OFFSET);
long sinceMidnight = (rightNow.getTimeInMillis() + offset) %
(24 * 60 * 60 * 1000);
System.out.println(sinceMidnight + " milliseconds since midnight")

how to get correct date diffrence

i want to compare a date with the current date and do something if the difference is 2 months or 6 or a year .. but i have a problem how to get the correct difference for example if the current month is 02 2015 and the other month is 10 2014 i will get 8 in difference but the actual difference is 4 .. how to do it ?
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat d = new SimpleDateFormat("dd");
SimpleDateFormat m = new SimpleDateFormat("MM");
SimpleDateFormat ye = new SimpleDateFormat("yyyy");
String day = d.format(c.getTime());
String month = m.format(c.getTime());
String year = ye.format(c.getTime());
int d1=Integer.parseInt(day);
int m1=Integer.parseInt(month);
int d2=25;
int m2=02;
int diff=d1-d2;
String s=String.valueOf(diff);
You are calculating your difference between two int, so it can't work.
You should calculate it between two dates or two long (in secondes or milliseconds)
long oneDay, today, delay;
oneDay = 1000*3600*24; //number of milliseconds in a day
today = Calendar.getInstance().getTimeInMillis();
delay = (TheDateYouWantToCompare - today)/oneDay;
if (delay >= 60*oneDay) { //more than 2 months
//your code
}else{
//your code
}
If TheDateYouWantToCompare and today are dates, it's almost the same :
delay = (TheDateYouWantToCompare.getTime() - today.getTime())/oneDay;
Edit :
Here it is how to get time in milliseconds.
String DateString = "31-12-2015";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date myDate = sdf.parse(DateString);
long timeInMilliseconds = myDate.getTime();
You could just use the difference in milliseconds between the 2 dates. Pre-compute the differences you need/want as constants and compare to the delta you have, for example:
static final long DAY = 1000 * 60 * 60 * 25;
static final long MONTH = DAY * 30;
...
int diff = d1 - d2;
if(diff > MONTH) {
//more than a month difference
}
If you need something more complex you should perhaps use a library such as Joda Time which will give a more comprehensive set of features to work with time.

Convert Date to Year and Month

I am writing an application in which I have to display a date . Now I want to convert that date into Year and Month from the Current Date.
My Date is Like - 29/03/2017.
I want to convert this date into Year and Months.
Sorry I think you are not able to understand my question. I want the Difference of current date and above date in year and months.
Sorry for my explanation.
You can use Joda Time and compute a Period between two LocalDate values (which is what you've got here) using months and years as the units.
example
LocalDate dob = new LocalDate(1992, 12, 30);
LocalDate date = new LocalDate(2010, 12, 29);
Period period = new Period(dob, date, PeriodType.yearMonthDay());
System.out.println(period.getYears() + " years and " +
period.getMonths() + " months");
I found my answer using Calender class .
First i find the difference between two days and using that days i found the years and months.
Here i post my code, which i think help to others.
int days = Integer.parseInt(Utility.getDateDiffString("29/03/2017"));
int years = days/365;
int remainingDays = days - (365*years);
int months = remainingDays/30;
getDateDiffString() Method. In this method we need to pass end date
public static String getDateDiffString(String endDate)
{
try
{
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date dateTwo = dateFormat.parse(endDate);
long timeOne = cal.getTimeInMillis();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "" + delta + "";
}
else {
delta *= -1;
return "" + delta + "";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
if your date's format is fixed, you can do it like this :
String myDate = "29/03/2017";
String newDate = myDate.subString(6, 10) + "-" + myDate.subString(3, 5)
this method to convert the normal string to date format
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("mm/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
after that you get the formal method
You Should use SimpleDateFormate !
For Example:--- You can get time & Date as you want:-
Date email_date = m.getSentDate();// this is date which you are getting
DateFormat date = new SimpleDateFormat("EEE MMM yyyy");
DateFormat time = new SimpleDateFormat("hh:mm aa");
String date_str=date.format(email_date);
String time_str=time.format(email_date);
Use Java Calendar class to get year from date
Calendar c=Calendar.getInstance();
SimpleDateFormat simpleDateformat=new SimpleDateFormat("yyyy MMM");
System.out.println(simpleDateformat.format(c.getTime()));
To get difference between two date
int diffInDays = (int)( (newerDate.getTime() - olderDate.getTime())
/ (1000 * 60 * 60 * 24) )
long timeDiff = (d1.getTime() - d2.getTime());
String diff=String.format("%d year(s) %d day(s) %d hour(s) %d min(s) %d sec(s)",(TimeUnit.MILLISECONDS.toDays(timeDiff)/365),TimeUnit.MILLISECONDS.toDays(timeDiff)%365,
TimeUnit.MILLISECONDS.toHours(timeDiff)
- TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS
.toDays(timeDiff)),
TimeUnit.MILLISECONDS.toMinutes(timeDiff)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(timeDiff)),
TimeUnit.MILLISECONDS.toSeconds(timeDiff)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(timeDiff)));
System.out.println(diff);
Specify correct date here in d1 & d2.Then you will get right answer of difference
First put your Date into a String variable as:
String dateToConvert = "29/03/2017";
Instantiate Calendar as:
Calendar convertedDate = Calendar.getInstance();
Set that date to calendar
convertedDate.set(dateToConvert);<br/>
Then use this line:
String datePicked = DateFormat.getDateInstance().format(convertedDate.getTime());
Output: Mar 29, 2017

Categories

Resources