Is there an existing android or java or joda-time function for converting minutes since midnight to time? I know how to do it for a 24 hour period without the am/pm bit. But I need to have the am/pm for some users.
This is for an android app. So the added benefit of using a standard function is that it will conform to the general preference of the user.
I suppose I can roll out my (buggy) own if such does not exist.
You could use Calendar and SimpleDateFormat to get that. Something like,
static DateFormat _sdf = new SimpleDateFormat("hh:mm a");
static String minutesSinceMidnight(int minutes) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.AM_PM, Calendar.AM);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.MINUTE, minutes);
return _sdf.format(cal.getTime());
}
Related
Need to get date-time in seconds from current date.
Want to add 2 days from current date-time and get value of 7 PM of result day.
I.E.
Current date-time is 1 January, 7:05 PM OR 6:55 PM, I should get value of 3 January, 7:00 PM in seconds.
P.S. - Can't use JODA Time & Java 8.
Did you try ThreeTenABP by Jake Wharton? https://github.com/JakeWharton/ThreeTenABP. You can use it also for android versions before api 26 (required for the new java.time.instant) and it has all the functionalities of the Java 8 api.
I would do:
LocalDate myDate;
myDate = LocalDate.now().plus(2, ChronoUnit.DAYS);
LocalDateTime myDateAtTime = myDate.atTime(19,0,0);
long millis = myDateAtTime.toEpochSecond(ZoneOffset.UTC);
Without using Java 8 you can do something like this:
public static void main(String[] args) throws Throwable {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 2);
c.set(Calendar.HOUR_OF_DAY, 19);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
System.out.println(c.getTimeInMillis() / 1000L); // Time in seconds in two days at 7:00 pm
}
You could also create a static method for this:
private static long timeInTwoDaysAt7pm() {
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, 2);
c.set(Calendar.HOUR_OF_DAY, 19);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTimeInMillis() / 1000L;
}
If java 8 is a no go, then you can use Calendar :
import java.util.Calendar
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 2);
calendar.set(Calendar.HOUR_OF_DAY, 19);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Not sure if this is a correct approach or any better solution is there.
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 2);
c.set(Calendar.HOUR_OF_DAY, 19);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
long timeInSeconds = c.getTime().getTime() / 100;
I have a Java program where I need to set a Calendar object to be midnight, so I followed the instructions from another posting on how to create a Java Date object of midnight today and midnight tomorrow, where you set the fields to be 0, like so:
calStart.set(Calendar.HOUR_OF_DAY, 0);
calStart.set(Calendar.MINUTE, 0);
calStart.set(Calendar.SECOND, 0);
calStart.set(Calendar.MILLISECOND, 0);
However, I am getting inconsistent results using Java 1.7.0_51. (Please no suggestions on using Jodatime, as I would like to use the base library only.)
Here is my test program:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
public class MidnightTester {
public static void runTestMidnight1() {
System.out.printf("runTestMidnight1() called\n");
TimeZone tz = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(1437004800000L);
cal.setTimeZone(tz);
System.out.printf("Original timestamp:\n");
printCalendarWithTimeZone(cal, tz);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.printf("Timestamp after setting to midnight:\n");
printCalendarWithTimeZone(cal, tz);
}
public static void runTestMidnight2() {
System.out.printf("runTestMidnight2() called\n");
TimeZone tz = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance();
cal.setTimeZone(tz);
cal.setTimeInMillis(1437004800000L);
System.out.printf("Original timestamp:\n");
printCalendarWithTimeZone(cal, tz);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
System.out.printf("Timestamp after setting to midnight:\n");
printCalendarWithTimeZone(cal, tz);
}
public static void printCalendarWithTimeZone(Calendar cal, TimeZone tz) {
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, MMMM dd, yyyy, hh:mm:ss aaa");
sdf.setTimeZone(tz);
System.out.printf("%d= %s\n", cal.getTimeInMillis(), sdf.format(cal.getTime()));
}
public static void main(String argv[]) {
runTestMidnight1();
runTestMidnight2();
}
}
Here is the output:
runTestMidnight1() called
Original timestamp:
1437004800000= Thursday, July 16, 2015, 12:00:00 AM
Timestamp after setting to midnight:
1436918400000= Wednesday, July 15, 2015, 12:00:00 AM
runTestMidnight2() called
Original timestamp:
1437004800000= Thursday, July 16, 2015, 12:00:00 AM
Timestamp after setting to midnight:
1437004800000= Thursday, July 16, 2015, 12:00:00 AM
As you can see, in runTestMidnight1(), the day changes from July 16 to July 15 after setting the time to midnight! I don't get that.
What's more weird is that in runTestMidnight2(), I swap only two lines, and the day correctly stays the same on July 16.
cal.setTimeZone(tz);
cal.setTimeInMillis(1437004800000L);
I am in America/Pacific time, in case that matters.
Can someone help me understand what's going on?
EDIT: Better Explanation
When we call setTimeInMillis(), the passed long values is assumed to be in UTC. and it calculates the time in calendar object time using user's timezone or if any timezone already available with Calendar object.
If there is no timezone passed then user's timezone gets set on calendar object. So the value '1437004800000L' considered to be in PST timezone and time gets calculated with PST timezone.
Calling setTimeZone() after setting time in millis is changing the timezone in Calendar object. So the calendar object time gets moved to UTC. This is the case of runTestMidnight1(). And that's why we see a shift in date because original time was in PST.
While in second method, the timezone is first set by setTimeZone() to UTC. So the time value is '1437004800000L' and considered timezone is UTC and calculated time would be in UTC. And you gets UTC time only.
And this problem gets reproduced only if user is in timezone which behind the UTC timezone.
Hope it clarifies.
They have used GWT to create a form which contains date pickers when user submits the form, dates selected shifts one day back. e.g. if i select 21/06/2015 it shifts to 20/06/2015. This is happening when users time zone is different from server time zone. When i debug it, i found that it shifts one day back while converting date to calendar because Date is client zone's Date and Date to Calendar conversion is happening in server side for sending it to marshalling(before sending request to rest service API for saving).
Following code is used for converting date to calendar.
Calendar cal = Calendar.getInstance();
int offset = date.getTimezoneOffset();
logger.info("Calendar Instance - " + cal);
cal.setTime(date);
logger.info("Calendar Instance after setting date - " + cal);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
logger.info("Calendar Instance after setting zeros - " + cal);
return cal;
In last log it displays one day less than actual date.
it works fine if i remove the following code.
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
for IST and PST but not to other timezones.
Please help.
I have a GregorianCalendar that I am am trying to set the time on. I am getting the date from one calendar and the time from another calendar. It mostly works, except for the 2AM hour of the DST switch day.
For example, with a date of 3/10/2013, a time of 2:40AM and a target output of 3/10/2013 2:40AM, I get 3/10/2013 3:40AM:
GregorianCalendar reportingDate = //some instance with a relevant date (in this case 3/10/2013)
GregorianCalendar targetTime = //some instance with a relevant time (in this case 2:40AM)
Calendar combination = Calendar.getInstance();
combination.set(Calendar.YEAR, reportingDate.get(Calendar.YEAR));
combination.set(Calendar.MONTH, reportingDate.get(Calendar.MONTH));
combination.set(Calendar.DAY_OF_YEAR, reportingDate.get(Calendar.DAY_OF_YEAR));
combination.set(Calendar.HOUR, targetTime.get(Calendar.HOUR));
combination.set(Calendar.AM_PM, targetTime.get(Calendar.AM_PM));
combination.set(Calendar.MINUTE, targetTime.get(Calendar.MINUTE));
combination.set(Calendar.SECOND, targetTime.get(Calendar.SECOND));
As soon as the code sets the AM_PM on the combination Calendar the time switches to 3:40AM. I would like it to not switch. I think this has to do with the target time Calendar being created as a time on the epoch date, but I would like the target time's specific date to not really matter...
Based on this output... I would think this is just how Java deals with DST? Seems like 2-3 AM goes into oblivion
See my comment below
final Calendar reportingDate = Calendar.getInstance();
reportingDate.set(Calendar.YEAR, 2013);
reportingDate.set(Calendar.MONTH, Calendar.MARCH);
reportingDate.set(Calendar.DAY_OF_MONTH, 10);
final Calendar targetTime = Calendar.getInstance();
targetTime.set(Calendar.AM_PM, Calendar.AM);
targetTime.set(Calendar.HOUR_OF_DAY, 3);
targetTime.set(Calendar.MINUTE, 0);
targetTime.set(Calendar.SECOND, 0);
targetTime.set(Calendar.MILLISECOND, 0);
final Calendar combination = Calendar.getInstance();
combination.set(Calendar.YEAR, reportingDate.get(Calendar.YEAR));
combination.set(Calendar.MONTH, reportingDate.get(Calendar.MONTH));
combination.set(Calendar.DAY_OF_YEAR, reportingDate.get(Calendar.DAY_OF_YEAR));
combination.set(Calendar.HOUR, targetTime.get(Calendar.HOUR));
combination.set(Calendar.AM_PM, targetTime.get(Calendar.AM_PM));
combination.set(Calendar.MINUTE, targetTime.get(Calendar.MINUTE));
combination.set(Calendar.SECOND, targetTime.get(Calendar.SECOND));
combination.set(Calendar.MILLISECOND, targetTime.get(Calendar.MILLISECOND));
final long timeAtCombined = combination.getTimeInMillis();
final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSSZ");
sdf.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
// subtract one minute
System.out.println(sdf.format(combination.getTime()));
combination.add(Calendar.MILLISECOND, -1);
System.out.println(sdf.format(combination.getTime()));
// millis # 3
System.out.println(sdf.format(new Date(timeAtCombined)));
// millis # 3 - 1ms
System.out.println(sdf.format(new Date(timeAtCombined - 1)));
Output
03/10/2013 03:00:00.000-0400
03/10/2013 01:59:59.999-0500
03/10/2013 03:00:00.000-0400
03/10/2013 01:59:59.999-0500
You're setting everything, except for the time zone (which contains the DST). Set that as well, and you should be okay.
This isn't really an answer to your question directly but you can avoid all of this craziness by going with Joda Time
They have really nailed the date/time/calendar thing down.
There is Java code,which is ran on 2 different environments and inserts records with JdbcTemplate to DB.
Results of its running are different for both envs. Particularly,for Date fields.
On first environment(Oracle XE) it produces record:
"12/03/2010";191094;"71697211000";3229;880323202;NULL;0;1;0;NULL;0;NULL
Second environment(Oracle non XE):
"12/03/2010 12:00:00";191094;"71697211000";3229;880323202;NULL;0;1;0;NULL;0;NULL
NLS_DATE_FORMAT(if it's crucial) for first env is DD-MON-RR,
for second env is DD-MON-RRRR
The question is,what Oracle settings may affect,that second env Date format is another?
should set following Calendar properties in Java code:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
instead of:
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, 0);
According to the documentation, HH refers to a 12-hour time. The 12 in the time you're retrieving is 12 midnight. What you want is HH24, which ges you a 24-hour time, starting at 00 for midnight.
If you don't want to show the time part, don't include a format string which includes the time part ("HH:MI:SS").
You've reset the time part to midnight, basically... there's no way of differentiating between a Calendar or Date set to exactly midnight and a Calendar or Date "without" a time part - because there's no such concept as a Calendar/Date with only a date part.
Now you may be able to have that in the database, depending on what types are available to you - but java.util.Date and java.util.Calendar always represent points in time, not just dates.
The reason it's showing 12 instead of 00 is because you're using "HH" instead of "HH24", as per lacqui's answer. I assume you don't really want to see the time at all though, given that you'll have reset it to midnight...
I'd recommend you extend one of the Calendar classes like this:
public class CalendarDateOnly extends GregorianCalendar {
public static Calendar getInstance() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMinimum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMinimum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMinimum(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cal.getActualMinimum(Calendar.MILLISECOND));
return cal;
}
}
Instantiate in this way:
Calendar june30 = CalendarDateOnly.getInstance();
june30.set(2000, Calendar.JUNE, 30);
/*
* Date : 2015-07-09
* Author : Bhuwan Prasad Upadhyay
*/
package com.developerbhuwan.date.utils;
import java.util.Calendar;
import java.util.Date;
/**
*
* #author developerbhuwan
*/
public class CalenderUtils {
public static Calendar getNewCalendarInstance() {
Calendar calendar = Calendar.getInstance();
return resetCalender(calendar);
}
public static Date resetDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return resetCalender(calendar).getTime();
}
public static Calendar resetCalender(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar;
}
public static void setTimeInCalendar(Calendar calendar, Date date) {
calendar.setTime(resetDate(date));
}
}