How to transform current Date in a specific Number in Java - java

I have the following Oracle SQL Statement in my SQL Select clause, which transform a date like 01.04.2015 into 78, 01.07.2015 into 79 and so on (the value of beginDate could be 01.04.2015 or 01.07.2015):
SELECT to_char(beginDate, 'q') + 4 * to_char(beginDate, 'yy') + 16
FROM myDateValuesTable;
Now it is important for me to transform always the current Date into the same values in Java by using the same kind of math expression. I have no idea, how I can programming these steps in Java? Here is a first idea:
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR); // the value is 2015
int month = calendar.get(Calendar.MONTH); // the value is 09
int quarter = (month / 3) + 1; // the value is 3
For the 01.04.2015 it must be transformed into 78 and for the 01.07.2015 into 79. How can I solve this problem?

Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
System.out.println(month / 3 + 1 + 4 * (year % 100) + 16);
Oracle 'q' returns the quarter of the year. This is obtained in Java by getting the month value and calculating month / 3 + 1.
Then, Oracle 'yy' returns the last two digits of the year. This is obtained in Java by getting the year value and calculating year % 100.
You can test it with the following code:
public static void main(String args[]) throws Exception {
System.out.println(getNumber("01.04.2015")); // prints 78
System.out.println(getNumber("01.07.2015")); // prints 79
}
private static int getNumber(String dateStr) throws ParseException {
Date date = new SimpleDateFormat("dd.MM.yyyy").parse(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
return month / 3 + 1 + 4 * (year % 100) + 16;
}

Related

How to get Current Year in YY Format in Java/Android [duplicate]

This question already has answers here:
Displaying the last two digits of the current year in Java
(7 answers)
Closed 5 years ago.
I am able to get Year in YYYY Format from my below Code. But I want in YY Format. Can anyone help?
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int hour = c.get(Calendar.HOUR_OF_DAY); // IF YOU USE HOUR IT WILL GIVE 12 HOUR USE HOUR_OF_DAY TO GET 24 HOUR FORMAT
int minutes = c.get(Calendar.MINUTE);
int date = c.get(Calendar.DATE);
int month = c.get(Calendar.MONTH) + 1; // in java month starts from 0 not from 1 so for december 11+1 = 12
int year = c.get(Calendar.YEAR);
yep :)
int year = c.get(Calendar.YEAR) % 100;
You could do:
int fourDigYear = c.get(Calendar.YEAR)
String yrStr = Integer.toString(digyear).substring(2);
int year = Integer.parseInt(yrStr);
for example if the Calendar year was the int 2014, "year" would come out as the integer 14. This ensures that any year put in it will ALWAYS export the numbers past "yy". So I guarantee you will have no problems with it until the year 10000.
EDIT:
To get this working for eternity, you can tweak it to this:
int digyear = c.get(Calendar.YEAR);
String yrStr = Integer.toString(digyear);
String yrStrEnd = yrStr.substring(yrStr.length() - 2);
int year = Integer.parseInt(yrStrEnd);

Java Calendar shows wrong amount of weeks when first week of month is defined as week in which 1 occurs

I've made a function that should get the number of weeks for a given month. For January, May, July and October, it should return 5 weeks.
However, it returns 5 for March, June, September. and November. Surprisingly, the total amount of weeks are correct (52).
public static int getNofWeeksWithFirstWeekStartingWhenFirstDayOfMonthOccurs(Calendar calendar) {
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
calendar.roll(Calendar.DATE, true);
}
int currentMonth = calendar.get(Calendar.MONTH);
int nextMonth = (currentMonth + 1) % 12;
int prePreviousMonth = (currentMonth + 12 - 2) % 12;
int nofWeeks = 0;
do {
int month = calendar.get(Calendar.MONTH);
if (month == nextMonth) {
nofWeeks++;
}
if (month == prePreviousMonth) {
break;
}
calendar.roll(Calendar.WEEK_OF_YEAR, true);
} while (true);
return nofWeeks;
}
public static void main(String[] args) {
int numWeeks;
int totalWeeks=0;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2016);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, Calendar.MAY);
numWeeks=getNofWeeksWithFirstWeekStartingWhenFirstDayOfMonthOccurs(calendar);
System.out.println("no of weeks " + numWeeks);
}
Output:
no of weeks 4
Month start is in Week that has first day. e.g.:
25 - 1 May
2 - 8 May
9 - 15 May
16 - 22 May
23 - 29 May
5 Weeks in May:
It sounds to me like you should:
Work out the first day of the month
Determine from that how many "extra" days are "borrowed" from the previous month (e.g. 0 if day 1 is a Monday; 1 if day 1 is a Tuesday etc)
Add that to the number of days in the regular month
Divide by 7 (with implicit truncation towards 0)
There's no need to do half the work you're currently doing.
Using java.util.Calendar, it would be something like:
// Note: day-of-week runs from Sunday (1) to Saturday (7).
// Entry 0 here is not used. We could do this without an array lookup
// if desired, but it's whatever code you think is clearest.
private static final int[] EXTRA_DAYS = { 0, 6, 0, 1, 2, 3, 4, 5 };
// Note: 0-based month as per the rest of java.util.Calendar
public static int getWeekCount(int year, int month) {
Calendar calendar = new GregorianCalendar(year, month, 1);
int dayOfWeekOfStartOfMonth = calendar.get(Calendar.DAY_OF_WEEK);
int extraDays = EXTRA_DAYS[dayOfWeekOfStartOfMonth];
int regularDaysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
int effectiveDaysInMonth = regularDaysInMonth + extraDays;
return effectiveDaysInMonth / 7;
}
If at all possible, I'd recommend using Joda Time or java.time instead, however.
With that code, the results for 2016 are:
January: 5
February: 4
March: 4
April: 4
May: 5
June: 4
July: 5
August: 4
September: 4
October: 5
November: 4
December: 4
From the comments I deduce that you want to count the number of weeks in a month starting at the 1st of the month.
You need to:
Set the day of the month to 1
add forward, not roll backward
start on Sunday instead of Monday
The code would be something like this:
public static int getNofWeeksWithFirstWeekStartingWhenFirstDayOfMonthOccurs(Calendar calendar) {
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
calendar.roll(Calendar.DATE, true);
}
int currentMonth = calendar.get(Calendar.MONTH);
int nextMonth = (currentMonth + 1) % 12;
int prePreviousMonth = (currentMonth + 12 - 2) % 12;
int nofWeeks = 0;
do {
int month = calendar.get(Calendar.MONTH);
if (month == currentMonth) {
nofWeeks++;
} else {
break;
}
calendar.add(Calendar.WEEK_OF_YEAR, 1);
} while (true);
return nofWeeks;
}
public static void main(String[] args) {
int numWeeks;
int totalWeeks=0;
for (int i = 0; i < 12; i++) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, 2016);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.MONTH, i);
numWeeks=getNofWeeksWithFirstWeekStartingWhenFirstDayOfMonthOccurs(calendar);
System.out.println("no of weeks " + numWeeks);
}
}
Output:
no of weeks 5
no of weeks 4
no of weeks 4
no of weeks 4
no of weeks 5
no of weeks 4
no of weeks 5
no of weeks 4
no of weeks 4
no of weeks 5
no of weeks 4
no of weeks 4

claculate the number of days between two dates without libraries

I need to claculate the number of days between two dates without using any date or calendar classes provided by any library.
Here's my idea:
numberOfDays = Math.abs((toYear - fromYear) * 365);
numberOfDays = numberOfDays + Math.abs((toMonth - fromMonth) * 12);
numberOfDays = numberOfDays + Math.abs((toDay - fromDay));
Thoughts?
How many days between the start date and the end of the month?
How many days in each full month until the end of the year?
How many days in each full year until the year of the end date (counting leap years)?
How many days in each full month until the last month?
How many days from the start of the last month until the end date?
Some of these numbers may be zero.
In Java 8 you can do the following:
long days = ChronoUnit.DAYS.between(LocalDate.of(2014, Month.MARCH, 01), LocalDate.of(2014, Month.FEBRUARY, 15));
Would something like this do?
//get 2 random dates
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = new Date();
Date date2 = sdf.parse("2014-9-12");
final long msInADay = 24*60*60*1000; //turn a day to ms
//divide time difference by the ms of a day
int difference = (int)((date2.getTime() - date1.getTime()) / msInADay);
System.out.println(Math.abs(difference));//Math.abs so you can subtract dates in any order.
EDIT after updating your question:
You can do this:
static int calcDayDiff(int startY, int startM, int startD, int endY, int endM, int endD){
int result = (startY - endY) * 365;
result += (startM - endM) * 31;
result += (startD - endD);
return Math.abs(result);
}
Testing with: System.out.println(calcDayDiff(2014,9,13,2013,8,12)); will print 397
Note though that this is not a very good solution since not every month contains 31 days and not every year 365. You can fix the month day difference by adding some simple logic inside the method to not always multiply by 31. Since it's an assignment i guess you will be ok to consider every year having 365 days.
public class test {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2014, 8, 1, 0, 0, 0);
Date s = cal.getTime();
Date e = new Date();
System.out.println(days(s,e));
}
public static int days(Date start, Date end){
double aTms = Math.floor(start.getTime() - end.getTime());
return (int) (aTms/(24*60*+60*1000));
}
}

In which year was the date the same as the original year?

It's my first question on this site, but I always found this site really useful.
What I mean with my question is:
you ask the person to give a date (eg. Fill in a date [dd-mm-yyyy]:
16-10-2013)
you than have to ask an interval between 2
years (eg. Give an interval [yyyy-yyyy]:1800-2000)
When the program runs, it has to show what day of the week the given date is. In this case it was a Wednesday. Than the program has to look in which year, in between the interval, the date 16 October also fell on a Wednesday.
So in the end it has to look something like this:
Fill in a date: [dd-mm-yyyy]: 16-10-2013
Give an interval [yyyy-yyyy]: 1900-2000
16 October was a wednesday in the following years:
1905 1911 1916 1922 1933 1939 1944 1950 1961 1967 1972 1978 1989 1995 2000
The full date is Wednesday 16 October, 2013
The small (or biggest) problem is, I am not allowed to use the DATE.function in java.
If someone can help me with the second part I would be really really happy, cause I have no idea how I am supposed to do this
To find out what day of the week the given date falls, I use the Zeller Congruence
class Day {
Date date; //To grab the month and year form the Date class
//In this class I check whether the giving date is in the correct form
int day;
int year1; //First interval number
int year2; //Second interval number
final static String[] DAYS_OF_WEEK = {
"Saturday", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday"
};
public void dayWeekInterval{
int interval.year1;
int interval.year2;
for(int i = year1; year1 =< year2; year1++) {
//check if the day of the week in the giving year, is the same as the
//original year.
}
}
public void dayOfTheWeek {
int m = date.getMonth();
int y = date.getYear();
if (m < 3) {
m += 12;
y -= 1;
}
int k = y % 100;
int j = y / 100;
int day = ((q + (((m + 1) * 26) / 10) + k + (k / 4) + (j / 4)) +
(5 * j)) % 7;
return day;
}
public string ToString(){
return "" + DAYS_OF_WEEK[day] + day;
}
Hey, I changed my code a bit, but I don't know how to knot the tie. Also I forgot to mention, I am not allowed to use the Date and Calendar function of java... And I pretty much did something wrong with the outlook..
Just a simple formula to find day for given date dd - MM - yyxx is,
( dd + m + xx + (xx/4) + (yy%4) ) % 7
% is modulus operator which is remainder in general
The answer got above will tell you day of week i.e. 0 : Mon 1: Tue .... 6 for Sun
Here,
dd - Date given
m - month value which is shown down in list calculated with MM value
yy - first two digits of supplied year
xx - last two digits of year
Now, m value calculation is,
0 for Jan and Oct
1 for May
2 for August
3 for Feb, March and Nov
4 for June
5 for Sept and Dec
6 for July and April
Remember if month supplied is Jan or Feb and the year supplied is leap then subtract 1 from m value in above table i.e. -1 for Jan and 2 for Feb
Leap Year Calculation is
if (yyyy % 4 == 0)
{
if( yyyy % 100 == 0)
{
return (yyyy % 400) == 0;
}
else
return true;
}
I hope rest of programming you can do.
This will help you find the day of week for supplied date and now you just need to add loop for all the years.
You cannot use Datebut can you use Calendar? Then this would be your code:
Calendar c = Calendar.getInstance();
c.set(2013, 9, 16); // month starts at zero
System.out.printf("Original date is: %tc\n", c);
int weekday = c.get(Calendar.DAY_OF_WEEK);
System.out.printf("Weekday of original date is [by number] %d\n", weekday);
for(int year = 1800; year < 2000; year++) {
c.set(Calendar.YEAR, year);
if(weekday == c.get(Calendar.DAY_OF_WEEK))
System.out.printf("%tc was same weekday!\n", c);
}

Convert a Julian Date to Regular Calendar Date

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);

Categories