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")
Related
I have an app where the user gets a task every day so what is the best method to use to keep track of time for a period of a day including any system condition even if the user turned his phone off.
I found a suggestion to use SystemClock.elapsedRealTime() but it doesn't include the phone being turned off ... so any other suggestions ?
Try to save (in SharedPreferences for example) the time of getting the task. Then when you want to get the period from this time to now you can do something like this:
long milliSecondsTriggering -> the milliseconds of the time of triggering the event;
long milliSecondsCurrentTime -> current time in milliseconds;
long periodSeconds = (milliSecondsCurrentTime - milliSecondsTriggering ) / 1000;
long elapsedDays = periodSeconds / 60 / 60 / 24;
try this method once:
call this method by passing long value of your time
public static String getDateDifferenceInDays(long timeInMillis) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
SimpleDateFormat simpleDateFormatParse = new SimpleDateFormat("dd MM yyyy");
Date serverDate = new Date(timeInMillis * 1000L);
Date localDate = new Date();
String strDay = "";
try {
Date dateServer = simpleDateFormatParse.parse(simpleDateFormat.format(serverDate));
Date dateLocal = simpleDateFormatParse.parse(simpleDateFormat.format(localDate));
long diff = dateServer.getTime() - dateLocal.getTime();
//Log.d(TAG, "server date-----" + dateServer + "-----local date----" + dateLocal);
long days = diff / (24 * 60 * 60 * 1000);
//long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
if (days >= 0) {
strDay = "Days left - " + days;
} else {
strDay = "Time elapsed";
}
} catch (ParseException e) {
e.printStackTrace();
}
return strDay;
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);
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.
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
I had written a function for Adding time as given below
private void Delay15Minute() {
String pkManifest = manifest.pkManifestNo;
manifest_helper = new manifest_helper(this);
cursor = manifest_helper.GetDeliveries(pkManifest);
cursor.moveToFirst();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.getString(cursor.getColumnIndex("PKDelivery"));
// String
// RevisedTime=cursor.getString(cursor.getColumnIndex("RevisedEstimatedDeliveryTime"));
String RevisedTime = "12:55";
// get hour and minute from time string
StringTokenizer st1 = new StringTokenizer(RevisedTime, ":");
int j = 0;
int[] val = new int[st1.countTokens()];
// iterate through tokens
while (st1.hasMoreTokens()) {
val[j] = Integer.parseInt(st1.nextToken());
j++;
}
// call time add method with current hour, minute and minutesToAdd,
// return added time as a string
String date = addTime(val[0], val[1], 15);
// Tioast the new time
Toast.makeText(this, "date is =" + date, Toast.LENGTH_SHORT).show();
}
}
public String addTime(int hour, int minute, int minutesToAdd) {
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
calendar.add(Calendar.MINUTE, minutesToAdd);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
return date;
}
I am getting the oupt of this as 01:10 as 12 hours fromat...
I need to get it in 13:10 format ie 24 hour format.....Please help me
You used hh in your SimpleDateFormat pattern. Thats the 12 hour format. Use kk instead, that gives you the hours of the day in a 24 hour format. See SimpleDateFormat.
Simply create the instance of Calendar and get 24 hr time by,
Calendar c = Calendar.getInstance();
int Hr24=c.get(Calendar.HOUR_OF_DAY);
int Min=c.get(Calendar.MINUTE);
Use this code
long date = System.currentTimeMillis();
SimpleDateFormat date1 = new SimpleDateFormat("dd-MM-yyyy"); // for current date
SimpleDateFormat time1 = new SimpleDateFormat("kk:mm:ss"); // for 24 hour time
SimpleDateFormat time2 = new SimpleDateFormat("hh:mm:ss"); // for 12 hour time
String dateString = date1.format(date); //This will return current date in 31-12-2018 format
String timeString1 = time1.format(date); //This will return current time in 24 Hour format
String timeString2 = time2.format(date); //This will return current time in 12 Hour format
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "24 hour Time - " + timeString1);
Log.e("TAG_1", "dd-MM-yyyy Date format - " + dateString);
than open your logcat to check result.