Apparently in a simple problem but I am being complicated with the treatment of dates. I need a date comparator that receives as parameters a date in yyyy-MM-dd format and a number (age) and that determines if it is above that number or below.
For example for 18, 1999-01-01 is above and would return true, but for 2010-01-01 false. If it were the year 2001, it would compare with the current month and year, that is, 2001-06-18 that was greater or less
I have this code using the gregorian api for the current date but I am unable.
I have this done
public static void main (String args[]) throws ParseException{
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//Date fechaInicial=(Date) dateFormat.parse("1999-01-01");
java.sql.Datedate1 = new Date(1999-01-01);
Calendar date2 = Calendar.getInstance();
boolean res = date(date1, date2);
}
public static boolean date(java.sql.Datedate1, Calendar date2 ){
//int year=18;
int y= date2.get(Calendar.YEAR)-18;
int m = date2.get(Calendar.MONTH)+1;
int d = date2.get(Calendar.DAY_OF_MONTH);
System.out.println(
String fechacompleta= y+"-"+m+"-"+d;
System.out.println(fechacompleta);
return ;
}
You can write your date method using java.time.LocalDate like this:
public static boolean date(LocalDate ld, int age) {
Period p = Period.between(ld, LocalDate.now());
return p.getYears() >= age;
}
It computes the Period between a certain date and now, and returns whether that period is greater than or equal to 18 years.
You can create a LocalDate like this:
LocalDate ld = LocalDate.parse("2001-12-23", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
And pass it into date:
if (date(ld, 18)) {
// 18 or above!
}
Related
This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
How do I calculate someone's age in Java?
(28 answers)
How can I calculate age in Java accurately given Date of birth
(4 answers)
Closed 4 years ago.
I want to convert date of birth into age.
This is my code.
String patientDOB = driver.findElement(id("patient_profile_widget_form_birthday")).getAttribute("value");
I'm getting date as: 03/01/1961
How could I convert this into age?
I want output like => 57 Years
Any idea? :)
using java 8
public int calculateAge(
LocalDate birthDate) {
// validate inputs ...
return Period.between(birthDate, LocalDate.now());
}
private static final DateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
String patientDOB = driver.findElement(id("patient_profile_widget_form_birthday")).getAttribute("value");
Date dateOfBirth = getDateFromString(patientDOB);
public Date getDateFromString(final String patientDOB) {
try {
return FORMATTER.parse(param);
} catch (ParseException e) {
throw new Exception("ParseException occurred while parsing date ", e);
}
}
public static int getAge(Date dateOfBirth) {
Calendar today = Calendar.getInstance();
Calendar birthDate = Calendar.getInstance();
birthDate.setTime(dateOfBirth);
if (birthDate.after(today)) {
throw new IllegalArgumentException("You don't exist yet");
}
int todayYear = today.get(Calendar.YEAR);
int birthDateYear = birthDate.get(Calendar.YEAR);
int todayDayOfYear = today.get(Calendar.DAY_OF_YEAR);
int birthDateDayOfYear = birthDate.get(Calendar.DAY_OF_YEAR);
int todayMonth = today.get(Calendar.MONTH);
int birthDateMonth = birthDate.get(Calendar.MONTH);
int todayDayOfMonth = today.get(Calendar.DAY_OF_MONTH);
int birthDateDayOfMonth = birthDate.get(Calendar.DAY_OF_MONTH);
int age = todayYear - birthDateYear;
// If birth date is greater than todays date (after 2 days adjustment of leap year) then decrement age one year
if ((birthDateDayOfYear - todayDayOfYear > 3) || (birthDateMonth > todayMonth)){
age--;
// If birth date and todays date are of same month and birth day of month is greater than todays day of month then decrement age
} else if ((birthDateMonth == todayMonth) && (birthDateDayOfMonth > todayDayOfMonth)){
age--;
}
return age;
}
Create a wrapper method that get you string as argument,
use:
String[] parts = string.split("/");
and select the 3rd item of the list.
then you just have to use:
int year = Calendar.getInstance().get(Calendar.YEAR);
to get your year. Then you just convert your year string into an int and substract them
This question already has answers here:
Does Java support Julian calendar?
(4 answers)
Closed 5 years ago.
I need to create a program that reads dates from a .csv file and convert it so that 13 days are added. I already did that but somehow it does not add the following dates as wished. It also goes over 30 days, which is not supposed to happen for example 2001-12-42.
public static void main(String[] args) throws FileNotFoundException, ParseException {
File fread = new File("src/daten-greg.csv");
File fwrite = new File("src/daten-jul.csv");
Scanner s = new Scanner(fread);
PrintStream print = new PrintStream(fwrite);
while(s.hasNext()) {
String[] line = s.nextLine().split(" ");
print.println(String.join(" ", Convert(line)));
}
s.close();
print.close();
}
private static String[] Convert(String[] value) throws ParseException {
for (int i = 0; i < value.length; i+=1)
value[i] = ToJulianisch(value[i]);
return value;
}
private static String ToJulianisch(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
Date d = sdf.parse(date);
Calendar c = Calendar.getInstance();
c.setTime(d);
int actDay = c.get(Calendar.DAY_OF_MONTH);
int actMonth = c.get(Calendar.MONTH) + 1 ;
int actYear = c.get(Calendar.YEAR);
actDay -= 13;
if(actDay - 13 < 1) {
actMonth -= 1;
if(actMonth < 1) {
actMonth = 12;
actYear -= 1;
}
Calendar k = Calendar.getInstance();
k.set(Calendar.YEAR, actYear);
k.set(Calendar.MONTH, actMonth - 1);
actDay = k.getActualMaximum(Calendar.DAY_OF_MONTH) + actDay;
}
return String.format("%s-%s-%s", actYear, actMonth, actDay);
}
You are subtracting 13 from actDay twice, first in actDay-=13 and again for if(actDay - 13 < 1). Inside the if block, you then add the value which is less than 14 to the number of days per month, resulting in overflowing the day of month.
If you simply want to subtract 13 days from the given date, you should use c.set(Calendar.DAY_OF_MONTH,actDay-13). This will handle the subtraction correctly inside the Calendar object and you can then use
actDay = c.get(Calendar.DAY_OF_MONTH);
int actMonth = c.get(Calendar.MONTH) + 1 ;
int actYear = c.get(Calendar.YEAR);
return String.format("%s-%s-%s", actYear, actMonth, actDay);
About some mistakes in your algorithm, see the answer of Heikki Mäenpää. I have also seen another mistake, namely a wrong pattern "yyyy-mm-dd" where "mm" stands for minutes (use "MM" for months).
But in general, you seem to try to reinvent the wheel. Even the old java.util.Calendar-API has a built-in way for the transformation from a gregorian to a julian calendar date, see my solution which is valid even for any date in the past with respect to cutover.
Your solution is only valid for dates where the distance between gregorian and julian calendar is 13 days (which is not true in the past, at the time of Pope Gregor's reform, there were only 10 days cut off).
public static void main(String[] args) throws ParseException {
String input = "2017-10-24";
System.out.println("Old API => " + toJulianisch(input)); // 2017-10-11
}
private static String toJulianisch(String date) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTimeZone(TimeZone.getTimeZone("GMT"));
gcal.setGregorianChange(new Date(Long.MIN_VALUE));
sdf.setCalendar(gcal);
Date d = sdf.parse(date);
gcal.setGregorianChange(new Date(Long.MAX_VALUE));
gcal.setTime(d);
return sdf.format(d);
}
As you can see, the old API-stuff even forces you to set the timezone to a fixed offset to avoid any possible timezone clutter. This is necessary because java.util.Calendar and java.util.Date are not real calendar dates but instants/moments.
Side notice:
I have written a time library (Time4J) which can even handle any historic date equal if it was gregorian or julian (or even swedish), equal when the historic year started (was in most cases not the first of January!) etc. Maybe it is overkill for your problem but I mention it for the case you really want to operate with true historic calendar dates.
I try to use current date in date formats but when I use different date formats this makes different results..at first I used this code:
private String getTodayDateString() {
Calendar cal = Calendar.getInstance();
int month=cal.get(Calendar.MONTH);
return Integer.toString(month);
}
and this return me 5 for result for month.
but when I use this code:
private String getTodayDateString2() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
return dateFormat.format(cal.getTime());
}
function returns me 14/6/2016 and this means month is calculated 6 in this dateformat.why?where is the problem?
months in calender starts from 0
0 =january
11=december
if you see the source code of Calendar class you will find public final static int JANUARY = 0;
similarily for december public final static int DECEMBER = 11;
Check the source code here
This question already has answers here:
Java string to date conversion
(17 answers)
Closed 8 years ago.
How can I get day and date from given Strings. For example:
String date="25-12-2014";
How to get date and day from given string?
Expected output is,
25
Thu
I got stuck when I tried this.
private static String getFormatedDate(String strDate) {
String result = "";
if(strDate != null) {
if (strDate.contains("-")) {
String[] dates = strDate.split("-");
for(int i=0;i<dates.length;i++) {
result = result + Utils.replaceDateFormat(dates[i].trim(),"MMM dd", "EE, M.dd") + ("-");
}
int lastIndex = result.lastIndexOf("-");
result = result.substring(0, lastIndex).trim();
}
else {
result = Utils.replaceDateFormat(strDate.trim(),"MMM dd", "EE, M.dd");
}
}
return result;
}
Utils:
public static String replaceDateFormat(String value, String actualFormat, String exceptedFormat) {
final int currentYear = Calendar.getInstance().get(Calendar.YEAR);
final SimpleDateFormat fromDate = new SimpleDateFormat(actualFormat);
final SimpleDateFormat toDate = new SimpleDateFormat(exceptedFormat);
Date convertedFromDate = null;
try {
convertedFromDate = fromDate.parse(value);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
final Calendar c1 = Calendar.getInstance();
c1.setTime(convertedFromDate);
c1.set(Calendar.YEAR, currentYear);
return toDate.format(c1.getTime());
}
Your methods are very convoluted for a relatively simple task. Why don't you use SimpleDateFormat? You can use the parse method. For example:
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(string);
And then you can get the required fields from there.
EDIT
To get the day of the week, you were right with this code:
Date d = date.parse(result);
Calendar c = Calendar.getInstance();
c.setTime(d);
int day=c.get(Calendar.DAY_OF_WEEK);
And then if you want it in the format above, you could just make an array filled with the days of the week:
String[] daysOfWeek = new String[]{"Sun","Mon"... etc}
String day = daysOfWeek[day - 1];
You can use the method from Calendar:
String date = "25-12-2014";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(format.parse(date));
int day = cal.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
DateFormatSymbols symbols = new DateFormatSymbols(new Locale("en"));
String[] days = symbols.getShortWeekdays();
System.out.printf("%02d %3s\n", day, days[dayOfWeek]);
The symbols can be set to your Locale zone.
if you are allowed to use java 8 you can give LocalDate a chance:
String date = "25-12-2014";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate ld = LocalDate.parse(date, formatter);
System.out.println(ld.getDayOfMonth() + ", " + ld.getDayOfWeek());
Output is:
25, THURSDAY
EDIT:
System.out.println(ld.getDayOfMonth() + ", " + ld.getDayOfWeek().substring(0, 3));
#No aNoNym suggestion is right, with the following you get
25, THU
I have a requirement, in which, I can provide startDate (27JUL14) and endDate (30JUN15), and dayOfWeek(4,5,6)
Day of week represent -
1 - Monday
2 - Tuesday
3 - Wednesday
4 - Thursday
5 - Friday
6 - Saturday
7 - Sunday
The duration between startDate and endDate is 6 months long, I need to get all the specific dates that match the provided dayOfWeek for the interval of time between StartDate and EndDate.
public void calculateScheduleDates(Date periodOfOperationFrom, Date periodOfOperationTo, String dow)
{
String[] weekDays = dow.replaceAll("\\[", "").replaceAll("\\]", "").split(",");
int[] dayOfWeek = new int[weekDays.length];
for (int i = 0; i < weekDays.length; i++)
{
try
{
dayOfWeek[i] = Integer.parseInt(weekDays[i]);
dateTime = (DateTime) DateTime.now().withDayOfWeek(dayOfWeek[i]);
System.out.println("DateTime :\t"+dateTime);
}
catch (NumberFormatException nfe) {};
}
}
I have tried to get weeks (Starting date of week)
public void getWeekDate(String beginDate, String finishDate)
{
System.out.println("Begindate "+ beginDate + "\t EndDate \t"+finishDate);
LocalDate startDate = new LocalDate(2014, 12, 1);
LocalDate endDate = new LocalDate(2015, 6, 30);
/* These are date format for startDate and endDate which are not working with 27JUL14 format.
This also needs to be changed
*/
LocalDate thisMonday = startDate.withDayOfWeek(DateTimeConstants.MONDAY);
if (startDate.isAfter(thisMonday))
{
startDate = thisMonday.plusWeeks(1); // start on next monday
}
else
{
startDate = thisMonday; // start on this monday
}
while (startDate.isBefore(endDate))
{
dates.add(startDate);
startDate = startDate.plusWeeks(1);
}
System.out.println("Size of List Of Date :\t"+dates+"\n"+dates.size());
}
Now I have tried to crate scheduleDates:
public void calculateFlightLegScheduleDates(LocalDate[] periodOfOperationFrom, String dow)
{
/*
* Process as per the Weeks received from dates list and set it to current week and process
* alongwith dow and for each date, loop in to set the schedule Record.
* */
// the incoming weeks "periodOfOperationFrom" in list format, and I need to set the week starting date to the weeks start dates even in future and find the week dates from the dow parameter. This is the point where I am facing challenge.
}
I need this solution in Java.
I have tried to use jodatime library, but couldn't get any specific result.
Note: Please note that, I need the specific dates between mentioned duration not just number of days.
Please help, I need this very much.
One possibility:
parse startDate/endDate
find the first date from startDate marching the wanted dayOfWeek
print that date then add 7 days and repeat until endDate is reached.
Sample code:
public class App {
public static void main(final String[] args) {
calculateScheduleDates("27JUL14", "30JUN15", DateTimeConstants.MONDAY);
}
private static void calculateScheduleDates(final String startDate, final String endDate, final int dayOfWeek) {
final DateTimeFormatter formatter = DateTimeFormat.forPattern("ddMMMy").withLocale(Locale.US);
final LocalDate end = LocalDate.parse(endDate, formatter);
LocalDate start = LocalDate.parse(startDate, formatter);
// find the first matching date
while (start.getDayOfWeek() != dayOfWeek) {
start = start.plusDays(1);
}
// compute and print results
while (start.compareTo(end) < 0) {
System.out.println(start.toString(formatter).toUpperCase());
start = start.plusDays(7);
}
}
}
Output:
28JUL14
04AUG14
...
15DEC14
22DEC14
...
22JUN15
29JUN15