Android get dates as long values - android

How do I get 11:59 PM of the previous night and 12:00 AM of tonight expressed as long values???
So many different date options I'm confused

you can use this calculation to do so.
//11:59 PM of the previous night and 12:00 AM of tonight
Calendar prevDate = Calendar.getInstance();
if(prevDate.get(Calendar.DATE)==1)
{
if(prevDate.get(Calendar.MONTH)==0)
{
prevDate.set(Calendar.YEAR, prevDate.get(Calendar.YEAR)-1);
prevDate.set(Calendar.MONTH,Calendar.DECEMBER);
prevDate.set(Calendar.DAY_OF_MONTH,31);
}
else
{
prevDate.set(Calendar.MONTH,prevDate.get(Calendar.MONTH)-1);
prevDate.set(Calendar.DAY_OF_MONTH, prevDate.getMaximum(Calendar.DAY_OF_MONTH));
}
}
else
{
prevDate.set(Calendar.DAY_OF_MONTH,prevDate.get(Calendar.DAY_OF_MONTH)-1);
}
prevDate.set(Calendar.HOUR_OF_DAY, 11);
prevDate.set(Calendar.MINUTE, 59);
Calendar currDate = Calendar.getInstance();
currDate.set(Calendar.HOUR_OF_DAY, 0);
currDate.set(Calendar.MINUTE, 0);
long prevDateLong = prevDate.getTimeInMillis();
long currDateLong = currDate.getTimeInMillis();
Log.i("", prevDate.toString()+" >>>>>>>> "+currDate.toString());
Log.i("", prevDateLong+" >>>>>>>>> "+currDateLong);

All Java dates are longs underneath. It's the number of milliseconds since midnight on 1-Jan-1970.
Date today = new SimpleDateFormat("yyyy-MMM-dd").parse("2012-Oct-28"); // today at midnight
long millis = today.getTime();
I'd recommend that you look at the java.util.Calendar class. It's not hard, just tedious.
http://www.exampledepot.com/search/luceneapi_node/Calendar

Related

How to check if current time is night

Is there Any service to check if the current time is night considering the winter and summer time changes ?
For example, the night in summer starts after 19:45 (in my local time), but in winter, night starts after 16:45.
My trial was:
Boolean isNight;
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
isNight = hour < 6 || hour > 18;
This code works only if if the night starts after 18:00, but night time changes according to the time in year.
You can use this sunrisesunset-lib and with a method like this and
your location you are able to find out it's night or not :
private boolean isNight(Location location) {
SunriseSunsetCalculator calculator = new SunriseSunsetCalculator(location, TimeZone.getTimeZone("GMT+3:30"));
Calendar now = Calendar.getInstance();
Calendar officialSunrise = calculator.getOfficialSunriseCalendarForDate(now);
Calendar officialSunset = calculator.getOfficialSunsetCalendarForDate(now);
return !(now.after(officialSunrise) && now.before(officialSunset));
}
one more code is working for me
String time1 = "01:00:00";
String time2 = "15:00:00";
LocalTime time = LocalTime.parse(time2);
if ((time.isAfter(LocalTime.of(20,11,13))) || (time.isBefore(LocalTime.of(14,49,0))))
{
System.out.println("true");
}
else
{
System.out.println("false");
}

Difference in days between two dates not giving proper results

I am trying to find difference in days between two dates.
I am using this approach
Calendar currentTimeCalendar = Calendar.getInstance();
Calendar postModificationTimeCalendar = Calendar.getInstance();
postModificationTimeCalendar.setTime(dateeventoccured); //dateeventoccured is in format = Tue Jan 03 00:44:46 EST 2017
long diffInMillis = currentTimeCalendar.getTimeInMillis() - postModificationTimeCalendar.getTimeInMillis();
long days = diffInMillis/ (24*60*60*1000);
Now the problem is suppose, I posted something yesterday at 5 pm ,When it is 12 in midnight today difference should be 1 and date should be like yesterday.
but the days remains 0 ,until next day 5 is reached.How to achieve that.
I want to show dates as today,yesterday and previous dates.
Try this (pass the 2 dates object in this function and you will get the exact diff. in days between 2 dates) :
public long getDays(Date d1, Date d2) {
if (d1 != null && d2 != null) {
long diff = getStartDate(d1).getTimeInMillis() - getStartDate(d2).getTimeInMillis();
return TimeUnit.MILLISECONDS.toDays(diff);
} else {
return -1;
}
}
public Calendar getStartDate(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
private int getDifferenceDay(Date DateStart, Date DateEnd) {
long diff = DateEnd.getTime() - DateStart.getTime();
long seconds = diff / 1000;
int minutes = (int) seconds / 60;
int hour = minutes / 60;
int day = hour/24;
return day;
}
Try using comareTo method it will return the date difference as integer value.
private void getDate() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-dd-mm");
String date1="2017-13-01";
String date2="2017-14-01";
Date d1=sdf.parse(date1);
Date d2=sdf.parse(date2);
int compare = d2.compareTo(d1);
Log.e("differece",""+compare);
}

Android TimePicker not returning user set time but realtime, convert to long

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

Android Formatter not giving correct time

so I have this code in Android
DateFormat formatter = new SimpleDateFormat("HH:mm", Locale.getDefault());
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millisUntilFinished);
textView.setText(formatter.format(calendar.getTime()));
here is how I am passing the values to this method, where the hours and minutes strings are "8" and "30" for example
Calendar c = Calendar.getInstance();
String s = ApplicationPreferences.getWakeUp(ActivityStage1.this);
String[] separated = s.split("\\:");
String hours = separated[0];
String minutes = separated[1];
c.add(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hours));
c.set(Calendar.MINUTE, Integer.parseInt(minutes));
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long timeUntilStageTwo = (c.getTimeInMillis() - System.currentTimeMillis());
startStageTwoTimer(timeUntilStageTwo);
So the value in the long millisUntilFinished is something like 58441666, which is around 16 hours and 20 min, but for some reason the time it shows at the end in the text view is with 3 hours more, I even tried with different locales passed to SimpleDateFormat, and still the same, why is that happening?
Your Calendar c is in your local UTC+3 timezone while the system clock runs at UTC. Hence the difference of 3 hours.
You can use setTimeZone() to set an explicit timezone on your calendar before computing its millisecond value.
If you prefer to do the computations yourself, you can get the user's timezone with TimeZone.getDefault() and then use getOffset(time) to get the millisecond offset at specified UTC time.

Android timer - 1 hour incorrect

I hope someone can help. Im trying to set up a timer that times from the start of a game and displays this time. The problem is that the following section of code gives me the wrong time. Its in the wrong format, and is out by an hour.
private long startTime;
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SS");
//Constructor:
startTime = System.currentTimeMillis();
public String getTime() {
long gameTime = System.currentTimeMillis() - startTime;
final Date date = new Date(gameTime);
return timeFormat.format(date);
}
It consistently gives me the output of 01:00:03:203. The seconds are correct, but the 1 hour shouldn't be there, and for format is 3 decimal places instead of the two I thought I specified.
Thank you very much!
Your date is epoch + gameTime. I think you're experiencing a daylight saving shift since the current DST in your location today doesn't match the DST at epoch.
Use a Calendar instead of a Date. Start with today and explicitly wipe out the hour, minute, etc. parts:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 3600000 + 60000 + 1000 + 1);
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SS");
System.out.println(timeFormat.format(cal.getTime()));
The output for the above is: 01:01:01.01
http://ideone.com/DyQcl
Substitute the numbers I have above with gameTime and you're done.
Of course, this may not work once your millisecond ticks exceed the day boundary.

Categories

Resources