It seems like, I couldn't find the answer for my problem, so here I am, first on Stackoverflow :)
The If statement tree that will be mentioned:
buttonSzamol.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Változók
int StartHour = 18;
int StartMin = 50;
int StopHour = 20;
int StopMin = 49;
int DayTimeIntervalStart = 6;
int DayTimeIntervalStop = 17;
int NightTimeIntervalLateStart = 18;
int NightTimeIntervalLateStop = 23;
int NightTimeIntervalEarlyStart = 0;
int NightTimeIntervalEarlyStop = 5;
int DayHoursTotal = 0;
int NightHoursTotal = 0;
int DayTimePricePerHour = Integer.parseInt(NappaliOraDij.getText());
int NightTimePricePerHour = Integer.parseInt(EjszakaiOraDij.getText());
int StartDay = Integer.parseInt((DatumStart.getText()).replace(".", ""));
int StopDay = Integer.parseInt((DatumStart.getText()).replace(".", ""));
//1 started hour
if( (StartDay == StopDay) && ( ( (StartHour == StopHour) && (StartMin < StopMin) ) || ( ((StartHour + 1) == StopHour) && (StartMin >= StopMin) ) ) ) {
if((DayTimeIntervalStart <= StartHour) && (StopHour <= DayTimeIntervalStop)) {
DayHoursTotal++;
}
if((NightTimeIntervalLateStart <= StartHour) && (StopHour <= NightTimeIntervalLateStop)) {
NightHoursTotal++;
}
} else/*More hours*/if( (StartDay == StopDay) && ( ( (StartHour < StopHour) && (StartMin <= StopMin) ) || ( (StartHour < StopHour) && (StartMin > StopMin) ) ) ) {
if( (StartHour < StopHour) && (StartMin < StopMin) ) {
if((DayTimeIntervalStart <= StartHour) && (StopHour <= DayTimeIntervalStop)) {
DayHoursTotal = DayHoursTotal + (StopHour - StartHour);
DayHoursTotal++;
}
if((NightTimeIntervalLateStart <= StartHour) && (StopHour <= NightTimeIntervalLateStop)) {
NightHoursTotal = NightHoursTotal + (StopHour - StartHour);
NightHoursTotal++;
}
}else if(( (StartHour < StopHour) && (StartMin >= StopMin) )) {
if((DayTimeIntervalStart <= StartHour) && (StopHour <= DayTimeIntervalStop)) {
DayHoursTotal = DayHoursTotal + (StopHour - StartHour);
if(StartMin != StopMin) {
DayHoursTotal--;
}
}
if((NightTimeIntervalLateStart <= StartHour) && (StopHour <= NightTimeIntervalLateStop)) {
NightHoursTotal = NightHoursTotal + (StopHour - StartHour);
if(StartMin != StopMin) {
NightHoursTotal--;
}
}
}
}
NappaliOrak.setText(Integer.toString(DayHoursTotal));
EjszakaiOrak.setText(Integer.toString(NightHoursTotal));
OrakOsszesen.setText(Integer.toString(DayHoursTotal + NightHoursTotal));
NappaliOsszeg.setText(Integer.toString(DayHoursTotal * DayTimePricePerHour));
EjszakaiOsszeg.setText(Integer.toString(NightHoursTotal * NightTimePricePerHour));
VegOsszeg.setText(Integer.toString((DayHoursTotal * DayTimePricePerHour) + (NightHoursTotal * NightTimePricePerHour)));
}
});
So, the problem in a nutshell is.
I've tried to create a parking fee calculator for my colleague at work.
The main idea is, that it needs to calculate how many Daytime and how many Nighttime hours the client started, and it needs to calculate the price of those hours. I've changed the StartHour/Min-StopHour/Min fields to straight integers to be more understanable. I don't know if there is a module for this, but I started doing this with a lot of If statements, where I just got tangled up. In the included pastebin, there is starting time 18:50 and stop time 20:49. If we input this data, the output should be 2 started day hours. Now if the minute is the same, it does not count as a started hour. But if we change the input to 20:51, then it started an another hour, so the DayHoursTotal should be equal to 3.
Thank you in advance, for any help. If you have more questions about my code or idea, just ask.
It seems that you are trying to calculate the started hours not just between 2 times, but also between different dates.
For this it is best to use the java.time package and more specifically the LocalDateTime class.
LocalDateTime.of(startYear, startMonth, startDay, startHour, startMinute)
LocalDateTimes in conjuction with the between() method from the Java 8 ChronoUnit class gets exactly what you need.
ChronoUnit.MINUTES.between(Temporal t1, Temporal t2)
PS: You don't need that many 'interval' variables.
Just the start hour of the day (dayTimeIntervalStart) and night (nightTimeIntervalLateStart) rate is enough.
The hours rates before and after can be derived from those two intervals.
Spoiler!! look away if you want to investigate further yourself! ;)
Here is a runnable code sample that shows the parking logic for >1 day:
(I have omitted the user input parsing/logic, because that depends on your implementation)
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class ParkingFee {
private static long hoursDifference(LocalDateTime ldt1, LocalDateTime ldt2) {
long minutesDiff = ChronoUnit.MINUTES.between(ldt1, ldt2);
long hoursDiff = Math.round(Math.ceil(minutesDiff/60.0));
return hoursDiff;
}
public static long hoursDifference(
int startDay, int startMonth, int startYear, int startHour, int startMinute,
int endDay, int endMonth, int endYear, int endHour, int endMinute) {
return hoursDifference(
LocalDateTime.of(startYear, startMonth, startDay, startHour, startMinute),
LocalDateTime.of(endYear, endMonth, endDay, endHour, endMinute));
}
public static int determineDayCycle(int dayTimeIntervalStart, int nightTimeIntervalLateStart) {
return nightTimeIntervalLateStart - dayTimeIntervalStart;
}
public static void main(String[] args) {
// Hourly rates
int dayTimePricePerHour = 5;
int nightTimePricePerHour = 10;
// Rate intervals
int dayTimeIntervalStart = 6;
int nightTimeIntervalLateStart = 18;
// Counted hours per rate
int dayHoursTotal = 0;
int nightHoursTotal = 0;
// Start date and time
int startYear = 2019;
int startMonth = 1;
int startDay = 1;
int startHour = 20;
int startMinute = 50;
// End date and time
int endYear = 2019;
int endMonth = 1;
int endDay = 3;
int endHour = 2;
int endMinute = 49;
// Calculate the hours difference
long hourDiff = hoursDifference(
startDay, startMonth, startYear, startHour, startMinute,
endDay, endMonth, endYear, endHour, endMinute);
System.out.println("Hour difference found: "+ hourDiff);
// Handle parking for full days
if (hourDiff > 24) {
int dayCycle = determineDayCycle(dayTimeIntervalStart, nightTimeIntervalLateStart);
long fullDays = hourDiff / 24;
nightHoursTotal += (24-dayCycle)*fullDays;
dayHoursTotal += dayCycle*fullDays;
hourDiff = hourDiff % 24;
}
// Handle the parking for less than full day
while (hourDiff > 0) {
if (startHour < dayTimeIntervalStart) { // Before the day interval -> night
nightHoursTotal++;
} else if(startHour < nightTimeIntervalLateStart) { // Before the night interval -> day
dayHoursTotal++;
} else { // After the day interval -> night
nightHoursTotal++;
}
startHour++;
if (startHour > 23) // At midnight reset the hour to 0
startHour = 0;
hourDiff--;
}
System.out.println("Day hours: "+ dayHoursTotal);
System.out.println("Night hours: "+ nightHoursTotal);
System.out.println("Total hours: "+ (dayHoursTotal + nightHoursTotal));
System.out.println("Day rate charged at "+ dayTimePricePerHour +": "+ (dayHoursTotal * dayTimePricePerHour));
System.out.println("Night rate charged at "+ nightTimePricePerHour +": "+ (nightHoursTotal * nightTimePricePerHour));
System.out.println("Total rate charged: "+ ((dayHoursTotal * dayTimePricePerHour) + (nightHoursTotal * nightTimePricePerHour)));
}
}
This outputs:
Hour difference found: 30
Day hours: 12
Night hours: 18
Total hours: 30
Day rate charged at 5: 60
Night rate charged at 10: 180
Total rate charged: 240
First, you need to parse the Integers differently. Your method is dangerous, e.g. loses information. Plus you need to make the code failsafe in case somebody tries to put in values that won't work. Refer to this question: How do I convert a String to an int in Java?
Apart from that, working with just minutes and hours is always difficult. I suggest using the absolute times in milliseconds which makes it far easier to do calculations. Refer to this question: Difference in hours of two Calendar objects
Time Zone
Your code and the other Answers fail to account for time zone anomalies. If you are tracking actual moments, when people actually parked, as opposed to theoretical 24-hour long days, then you must account for anomalies such as Daylight Saving Time (DST). Politicians around the world have shown a penchant for redefining the time zone(s) in their jurisdiction. So days can be any length, such as 25-hours long, 23-hours, 23.5 hours, 24.25, or others.
A time zone is a history of the past, present, and future changes to the offset-from-UTC used by the people of a particular region.
The LocalDateTime class is exactly the wrong class to use for this purpose. That class intentionally has no concept of time zone or offset-from-UTC. You can use it as a building block piece in your code, but it must be assigned a ZoneId to determine an actual moment via the ZonedDateTime class.
ZoneId
Specify your time zone.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Assemble date, time, & zone to determine a moment
Assemble your date and time-of-day.
LocalDate startDate = LocalDate.of( 2019 , 1 , 23 ) ; // 23rd of January in 2019.
LocalTime startTime = LocalTime.of( 18 , 50 ) ; // 6:50 PM.
ZonedDateTime startMoment = ZonedDateTime.of( startDate , startTime , z ) ;
LocalDate stopDate = LocalDate.of( 2019 , 1 , 23 ) ; // 23rd of January in 2019.
LocalTime stopTime = LocalTime.of( 20 , 50 ) ; // Two hours later, exactly — maybe! Depends on any anomalies at that time in that zone.
ZonedDateTime stopMoment = ZonedDateTime.of( stopDate , stopTime , z ) ;
➥ Note that in this example, we may have a span of time of exactly 2 hours, but maybe not. It might be 3 hours or some other length of time, depending on anomalies scheduled for that date at that time in that zone.
Elapsed time
To calculate elapsed time it terms of days (24-hour chunks of time, unrelated to the calendar), hours, minutes, and seconds, use Duration. (For year-months-days, use Period.)
Duration d = Duration.between( startMoment , stopMoment ) ;
Interrogate for entire span-of-time in terms of whole hours.
long hours = d.toHours() ; // Entire duration as count of whole hours.
Half-Open
In the included pastebin, there is starting time 18:50 and stop time 20:49. If we input this data, the output should be 2 started day hours. Now if the minute is the same, it does not count as a started hour. But if we change the input to 20:51, then it started an another hour, so the DayHoursTotal should be equal to 3.
This approach is know as Half-Open, when the beginning is inclusive, while the ending is exclusive. This is commonly used in date-time handling. The Duration and Period classes apply this approach.
But be careful about matching the minute number alone. Your date-time objects might be holding seconds and/or a fractional second, which would throw off your algorithm. As a habit, truncate your date-time objects explicitly if there is any possibility of smaller granularity than you want. For example, ZonedDateTime.truncatedTo.
Rate changes
Obviously, rate changes complicate matters. The other Answers seem to have covered this, so I'll not repeat. But I can add a big tip: See the ThreeTen-Extra for its classes Interval and LocalDateRange that may be of help to you. They include handy comparison methods for overlaps, contains, abuts, and so on.
divide et impera
Cutting down the big logic in small blocks make it easier to achieve
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
class Scratch {
static int StartHour = 18;
static int StartMin = 50;
static int StopHour = 20;
static int StopMin = 48;
static int DayTimeIntervalStart = 6;
static int DayTimeIntervalStop = 17;
static int NightTimeIntervalLateStart = 18;
static int NightTimeIntervalLateStop = 23;
static int NightTimeIntervalEarlyStart = 0;
static int NightTimeIntervalEarlyStop = 5;
static int DayTimePricePerHour = 10;
static int NightTimePricePerHour = 5;
static LocalTime dayStart = LocalTime.of(DayTimeIntervalStart, 0);
static LocalTime dayStop = LocalTime.of(DayTimeIntervalStop, 0);
static LocalTime nightEarlyStart = LocalTime.of(NightTimeIntervalEarlyStart, 0);
static LocalTime nightEarlyStop = LocalTime.of(NightTimeIntervalEarlyStop, 0);
static LocalTime nightLateStart = LocalTime.of(NightTimeIntervalLateStart, 0);
static LocalTime nightLateStop = LocalTime.of(NightTimeIntervalLateStop, 0);
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2019, 1, 1, StartHour, StartMin);
LocalDateTime stop = LocalDateTime.of(2019, 1, 1, StopHour, StopMin);
for(int i = 0; i < 3; i++){
stop = stop.plusMinutes(1L);
System.out.println(process(start, stop));
System.out.println("******");
}
stop = stop.plusDays(1L);
System.out.println(process(start, stop));
System.out.println("******");
}
public static int process(LocalDateTime start, LocalDateTime stop){
System.out.println(String.format("checking between %s and %s", start, stop));
if(stop.toLocalDate().isAfter(start.toLocalDate())){
// start and stop not on the same date
// split the computation, first currentDay then the rest
LocalDateTime endOfDay = LocalDateTime.of(start.toLocalDate(), LocalTime.MAX);
int resultForCurrentDay = process(start, endOfDay);
// not for the rest
LocalDateTime startOfNextDay = LocalDateTime.of(start.toLocalDate().plusDays(1L), LocalTime.MIN);
int resultForRest = process(startOfNextDay, stop);
return resultForCurrentDay + resultForRest;
}else{
// start and stop on the same date
return processIntraDay(start, stop);
}
}
private static int processIntraDay(LocalDateTime start, LocalDateTime stop) {
int result = 0;
LocalTime startTime = start.toLocalTime();
LocalTime stopTime = stop.toLocalTime();
// step 1: check early morning
result += checkBoundaries(startTime, stopTime, nightEarlyStart, nightEarlyStop, NightTimePricePerHour);
// step 2: check day time
result += checkBoundaries(startTime, stopTime, dayStart, dayStop, DayTimePricePerHour);
// step 3: check late night
result += checkBoundaries(startTime, stopTime, nightLateStart, nightLateStop, NightTimePricePerHour);
return result;
}
private static int checkBoundaries(LocalTime startTime, LocalTime stopTime, LocalTime lowerBoundary, LocalTime upperBoundary, int priceRatePerHour) {
// check if the period [start;stop] is crossing the period [lowerBoundary;upperBoundary]
if(stopTime.isAfter(lowerBoundary) && startTime.isBefore(upperBoundary)){
// truncate start time to not be before lowerBoundary
LocalTime actualStart = (startTime.isBefore(lowerBoundary))?lowerBoundary:startTime;
// symetrically, truncate stop to not be after upperBounday
LocalTime actualStop = (stopTime.isAfter(upperBoundary))?upperBoundary:stopTime;
// now that we have the proper start and stop of the period, let's compute the price of it
return compute(actualStart, actualStop, priceRatePerHour);
}else{
return 0;
}
}
private static int compute(LocalTime startTime, LocalTime stopTime, int pricePerHour) {
Duration duration = Duration.between(startTime, stopTime);
int hours = (int) duration.toHours();
long minutes = duration.toMinutes();
if(minutes % 60 > 0L){
// hour started, increasing the number
hours++;
}
int result = hours * pricePerHour;
System.out.println(String.format("%d hours at %d price/h => %d", hours, pricePerHour, result));
return result;
}
}
Went directly for the calculation of the final price. Updating to store total number of day hours and night hours should be much of a challenge
Result of my exemple:
checking between 2019-01-01T18:50 and 2019-01-01T20:49
2 hours at 5 price/h => 10
10
******
checking between 2019-01-01T18:50 and 2019-01-01T20:50
2 hours at 5 price/h => 10
10
******
checking between 2019-01-01T18:50 and 2019-01-01T20:51
3 hours at 5 price/h => 15
15
******
checking between 2019-01-01T18:50 and 2019-01-02T20:51
checking between 2019-01-01T18:50 and 2019-01-01T23:59:59.999999999
5 hours at 5 price/h => 25
checking between 2019-01-02T00:00 and 2019-01-02T20:51
5 hours at 5 price/h => 25
11 hours at 10 price/h => 110
3 hours at 5 price/h => 15
175
******
Might need more tests to ensure it's good in all conditions but should be a usefull starting point for you
I want to calculate the difference between a certain date and the current time.
int month = 9;
int day = 17;
int year = 2013;
Calendar date = new GregorianCalendar(year, month, day);
int miliseconds= (int) (System.currentTimeMillis() - calendar.getTimeInMillis());
System.out.println(msToString(second));
String msToString(int ms) {
return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")).format(new Date(ms));
}
the output is
13091-13091/? D/GTA: 1970-01-08 15:00:20.287
I want to get the amount of days, hours,minutes and seconds remaining.
What do I wrong?
you could try something like the following method
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TimeToGoCalculator {
/**
* #param args
*/
public static void main(String[] args) {
int month = 8;
int day = 19;
int year = 2013;
Calendar calendar = new GregorianCalendar(year, month, day);
int timeToGo = (int) (calendar.getTimeInMillis() - System.currentTimeMillis())/1000;
System.out.println(secondsToString(timeToGo));
}
private static String secondsToString(int seconds) {
int days = seconds / 24 / 3600;
int hours = (seconds - (days * 24 * 3600 )) / 3600;
int minutes = (seconds - (days * 24 * 3600 + hours * 3600)) / 60;
seconds = (seconds - (days * 24 * 3600 + hours * 3600 + minutes * 60));
return "The remaining time is "+days+" days, "+hours+" hours, "+minutes+
" minutes, and "+seconds+" seconds.";
}
}
That should give you the output you're looking for.
Notice that, when creating the GregorianCalendar object, the month is 0-indexed, so September would be = 8.
Use Joda Time library
Period class can help.
int month = 9;
int day = 17;
int year = 2013;
int hour= 0;
int minute =0;
int second =0;
int millisecond = 0;
DateTime dt1 = new DateTime(); //now
DateTime dt2 = new DateTime(year, month, day, hour, minute, second, millisecond);
//assuming dt1 is before dt2:
Period period = new Period(dt1, dt2, PeriodType.dayTime());
/*
periodType.dayTime()):
Gets a type that defines all standard fields from days downwards.
days
hours
minutes
seconds
milliseconds
*/
PeriodFormatter periodFormatter = new PeriodFormatterBuilder()
.printZeroAlways()
.minimumPrintedDigits(2)
.appendDays().appendSuffix("days ")
.appendHours().appendSuffix("hours ")
.appendMinutes().appendSuffix("minutes ")
.appendSeconds().appendSuffix("seconds ");
.toFormatter();
System.out.println(periodFormatter.print(period));
Are you able to use external libraries? Then Joda Time can help you, especially the Period class.
It has a constructor for two time instants and gives you the difference between the time instants in years/months/days/hours/seconds/milliseconds.
Your second variable holds an amount of milliseconds between the two dates, not a new date. You need to do some calculation using these milliseconds to get an amount of days, for instance.
You could do something like this:
int minutes = second/1000/60; // millis to seconds, seconds to minutes
to get an amount of minutes, then convert to hours, and so on.
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 9 years ago.
hello I am trying to calculate how many days are left in a pregnancy term but I think my algorithm is incorrect
public int getDaysPregnantRemainder_new() {
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
long diffDays = 280 - ((getDueDate().getTime() - calendar.getTime()
.getTime()) / (24 * 60 * 60 * 1000));
return (int) Math.abs((diffDays) % 7);
}
I am basing it off of a 280 day term, getDueDate() is a Date object and getTime() returns millisecond unix time
On some real world days the number reported is off by one, sometimes, and I am starting to think my algorithm is just wrong, or the millisecond time get gradually further and further off, or the millisecond time is not precise enough, or the gregorian calendar function rounds weird.
All in all I'm not sure, any insight appreciated
I don't know about your algorithm, but this (is basically) the one I used while tracking my wife's pregency...nerds...
Save yourself a lot of "guess" work and get hold of Joda-Time
public class TestDueDate {
public static final int WEEKS_IN_PREGNANCY = 40;
public static final int DAYS_IN_PREGNANCY = WEEKS_IN_PREGNANCY * 7;
public static void main(String[] args) {
DateTime dueDate = new DateTime();
dueDate = dueDate.plusDays(DAYS_IN_PREGNANCY);
System.out.println("dueDate = " + dueDate);
DateTime today = DateTime.now();
Days d = Days.daysBetween(today, dueDate);
int daysRemaining = d.getDays();
int daysIn = DAYS_IN_PREGNANCY - daysRemaining;
int weekValue = daysIn / 7;
int weekPart = daysIn % 7;
String week = weekValue + "." + weekPart;
System.out.println("Days remaining = " + daysRemaining);
System.out.println("Days In = " + daysIn);
System.out.println("Week = " + week);
}
}
This will output...
dueDate = 2014-02-25T14:14:31.159+11:00
Days remaining = 279
Days In = 1
Week = 0.1
I want to convert from Gregorian to Hijri(Islamic) date and I need a java class for this converting. I want to give it an Gregorian date in format of "yyyy/mm/dd" as string and it give me the Hijri date in the same format. can anyone help me?
Firstly, separate out the conversion part from the formatting/parsing part. You can deal with those easily later - and there are lots of questions on Stack Overflow about that.
Personally I'd use Joda Time, which typically makes life much simpler. For example:
import org.joda.time.Chronology;
import org.joda.time.LocalDate;
import org.joda.time.chrono.IslamicChronology;
import org.joda.time.chrono.ISOChronology;
public class Test {
public static void main(String[] args) throws Exception {
Chronology iso = ISOChronology.getInstanceUTC();
Chronology hijri = IslamicChronology.getInstanceUTC();
LocalDate todayIso = new LocalDate(2013, 3, 31, iso);
LocalDate todayHijri = new LocalDate(todayIso.toDateTimeAtStartOfDay(),
hijri);
System.out.println(todayHijri); // 1434-05-19
}
}
(It feels like there should be a cleaner way of converting dates between chronologies, but I couldn't find one immediately.)
Java 8 is built-in supporting Hejrah Date
example:
import java.time.*;
import java.time.chrono.HijrahChronology;
Date date = new Date(); // Gregorian date
Calendar cl=Calendar.getInstance();
cl.setTime(date);
HijrahDate islamyDate = HijrahChronology.INSTANCE.date(LocalDate.of(cl.get(Calendar.YEAR),cl.get(Calendar.MONTH)+1, cl.get(Calendar.DATE)));
//OUTPUT: Hijrah-umalqura AH 1436-02-03
just use Google for example here copied from the link given:
import java.util.Calendar;
/**
* Gregorian-Hijri Dates Converter
*
*
* This Code is used to convert Gregorian dates to Hijri Dates
*
*
*/
public class DateHigri {
static double gmod(double n,double m) {
return ((n % m) + m) % m;
}
static double[] kuwaiticalendar(boolean adjust) {
Calendar today = Calendar.getInstance();
int adj=0;
if(adjust){
adj=0;
}else{
adj=1;
}
if (adjust) {
int adjustmili = 1000 * 60 * 60 * 24 * adj;
long todaymili = today.getTimeInMillis() + adjustmili;
today.setTimeInMillis(todaymili);
}
double day = today.get(Calendar.DAY_OF_MONTH);
double month = today.get(Calendar.MONTH);
double year = today.get(Calendar.YEAR);
double m = month + 1;
double y = year;
if (m < 3) {
y -= 1;
m += 12;
}
double a = Math.floor(y / 100.);
double b = 2 - a + Math.floor(a / 4.);
if (y < 1583)
b = 0;
if (y == 1582) {
if (m > 10)
b = -10;
if (m == 10) {
b = 0;
if (day > 4)
b = -10;
}
}
double jd = Math.floor(365.25 * (y + 4716)) + Math.floor(30.6001 * (m + 1)) + day
+ b - 1524;
b = 0;
if (jd > 2299160) {
a = Math.floor((jd - 1867216.25) / 36524.25);
b = 1 + a - Math.floor(a / 4.);
}
double bb = jd + b + 1524;
double cc = Math.floor((bb - 122.1) / 365.25);
double dd = Math.floor(365.25 * cc);
double ee = Math.floor((bb - dd) / 30.6001);
day = (bb - dd) - Math.floor(30.6001 * ee);
month = ee - 1;
if (ee > 13) {
cc += 1;
month = ee - 13;
}
year = cc - 4716;
double wd = gmod(jd + 1, 7) + 1;
double iyear = 10631. / 30.;
double epochastro = 1948084;
double epochcivil = 1948085;
double shift1 = 8.01 / 60.;
double z = jd - epochastro;
double cyc = Math.floor(z / 10631.);
z = z - 10631 * cyc;
double j = Math.floor((z - shift1) / iyear);
double iy = 30 * cyc + j;
z = z - Math.floor(j * iyear + shift1);
double im = Math.floor((z + 28.5001) / 29.5);
if (im == 13)
im = 12;
double id = z - Math.floor(29.5001 * im - 29);
double[] myRes = new double[8];
myRes[0] = day; // calculated day (CE)
myRes[1] = month - 1; // calculated month (CE)
myRes[2] = year; // calculated year (CE)
myRes[3] = jd - 1; // julian day number
myRes[4] = wd - 1; // weekday number
myRes[5] = id; // islamic date
myRes[6] = im - 1; // islamic month
myRes[7] = iy; // islamic year
return myRes;
}
static String writeIslamicDate() {
String[] wdNames = {"Ahad", "Ithnin", "Thulatha", "Arbaa", "Khams",
"Jumuah", "Sabt"};
String[] iMonthNames = {"Muharram", "Safar", "Rabi'ul Awwal",
"Rabi'ul Akhir", "Jumadal Ula", "Jumadal Akhira", "Rajab",
"Sha'ban", "Ramadan", "Shawwal", "Dhul Qa'ada", "Dhul Hijja"};
// This Value is used to give the correct day +- 1 day
boolean dayTest=true;
double[] iDate = kuwaiticalendar(dayTest);
String outputIslamicDate = wdNames[(int) iDate[4]] + ", " + iDate[5] + " "
+ iMonthNames[(int) iDate[6]] + " " + iDate[7] + " AH";
return outputIslamicDate;
}
}
Try ummalqura-calendar which implements java.util.Calendar.
Using this calendar you can convert from Umm Al-Qura to Gregorian and vice versa,
and also you can use java.text.SimpleDateFormat to format dates.
sample way to convert date on android platform import
import org.joda.time.Chronology;
import org.joda.time.DateTime;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.chrono.IslamicChronology;
import org.joda.time.LocalDate;
then
implements HijriDatePickerDialog.OnDateSetListener
on onDateSet method
#Override
public void onDateSet(HijriDatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
Chronology iso = ISOChronology.getInstanceUTC();
Chronology hijri = IslamicChronology.getInstanceUTC();
DateTime dtHijri = new DateTime(year,monthOfYear,monthOfYear,dayOfMonth,dayOfMonth,hijri);
DateTime dtIso = new DateTime(dtHijri, iso);
Log.i("converted date" ,String.valueOf(dtIso));
}
For android API 26 and above you can use
import java.time.chrono.HijrahDate
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
HijrahDate.now()
}
It is a build-in class in Java.
How do I convert a 7-digit julian date into a format like MM/dd/yyy?
Found a useful site: http://www.rgagnon.com/javadetails/java-0506.html
This should do the trick:
public static int[] fromJulian(double injulian) {
int jalpha,ja,jb,jc,jd,je,year,month,day;
double julian = julian + HALFSECOND / 86400.0;
ja = (int) julian;
if (ja>= JGREG) {
jalpha = (int) (((ja - 1867216) - 0.25) / 36524.25);
ja = ja + 1 + jalpha - jalpha / 4;
}
jb = ja + 1524;
jc = (int) (6680.0 + ((jb - 2439870) - 122.1) / 365.25);
jd = 365 * jc + jc / 4;
je = (int) ((jb - jd) / 30.6001);
day = jb - jd - (int) (30.6001 * je);
month = je - 1;
if (month > 12) month = month - 12;
year = jc - 4715;
if (month > 2) year--;
if (year <= 0) year--;
return new int[] {year, month, day};
}
Starting with Java 8, this becomes a one-liner to get the LocalDate:
LocalDate.MIN.with(JulianFields.JULIAN_DAY, julianDay)
.format(DateTimeFormatter.ofPattern("MM/dd/yyyy"));
Where julianDay is your 7-digit number.
simple way is here and this will return approx 100% accurate information.
String getDobInfo(double doubleString){
SweDate sweDate = new SweDate(doubleString);
int year = sweDate.getYear();
int month = sweDate.getMonth();
int day = sweDate.getDay();
// getting hour,minute and sec from julian date
int hour = (int) Math.floor(sweDate.getHour());
int min = (int) Math
.round((sweDate.getHour() - Math.floor(hour)) * 60.0);
int sec = (int) (((sweDate.getHour() - Math.floor(hour)) * 60.0 - Math
.floor(min)) * 60.0);
return "DOB:(DD:MM:YY) "+day+":"+month+":"+year+" TOB:(HH:MM:SS) "+hour+":"+min+":"+sec;
}
download the Swiss Ephemeris library and enjoy coding!!!
Do you really mean a Julian date, like astronomers use? Ordinal dates, which are specified as a year (four digits) and the day within that year (3 digits), are sometimes incorrectly called Julian dates.
static String formatOrdinal(int year, int day) {
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.DAY_OF_YEAR, day);
Date date = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
return formatter.format(date);
}
This will give you the date at 00:00 local time; you may want to set the timezone on the calendars to GMT instead, depending on the application.
I see there are enough answers already provided. But any calendar related question is only half answered without mentioning joda-time ;-). Here is how simple it is with this library
// setup date object for the Battle of Hastings in 1066
Chronology chrono = JulianChronology.getInstance();
DateTime dt = new DateTime(1066, 10, 14, 10, 0, 0, 0, chrono);