I am using the following code to check the birthday of a person:
public class Test_Year {
static int yearsInterval =1;
static int yearsSpecial =0;
static Date dateYearsReg;
public static void main(String[] args){
yearsToNotify(2013, "0001-10-02");
}
public static void yearsToNotify(int yearsElapsedSinceBirth, String dateOfBirth){
Date dt = Convert(d);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
System.out.println();
yearsSpecial = yearsInterval*(1+(years/yearsInterval));
System.out.println(yearsSpecial);
cal.add(Calendar.YEAR, yearsSpecial);
dateYearsReg = cal.getTime();
System.out.println(dateYearsReg);
}
public static Date Convert(String S){
String dateStr = S;
Date d1 = null ;
try {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
d1 = f.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return d1;
}
}
Ideally the above should give me the next birthday and the year should be 2014, however I get the year as 2015. The system date being todays date that is first of October 2014. Any hints?
In the baove if I give a call like: yearsToNotify(41, "1972-10-17"); I get the correct values. Seems this is a problem with results when I use the year as 0001.
I believe the problem stems from this line
cal.add(Calendar.YEAR, yearsSpecial);
If we look at the javadoc for ADD we see it is this
public abstract void add(int field,
int amount)
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:
Instead you want to be using set:
cal.set(Calendar.YEAR, yearsSpecial);
Related
I'm trying to complete the task named Java Date and Time on HackerRank.
Task
You are given a date. You just need to write the method, getDay, which
returns the day on that date.For example, if you are given the date,
August 14th 2017, the method should return MONDAY as the day on that
date.
I tried my best to do the task but I get either the null result or NullPointerException error. I wonder where do I do wrong. Below is my code:
Thanks in advance!
My Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
System.out.println(getDay(day, month, year));
}
public static String getDay(String day, String month, String year) {
Calendar cal = Calendar.getInstance();
cal.set(Integer.valueOf(year), (Integer.valueOf(month) - 1), Integer.valueOf(day));
return cal.getDisplayName(cal.get(Calendar.DAY_OF_WEEK), Calendar.LONG, Locale.getDefault());
}
}
Your return is off; you don't want cal.get in the first column of cal.getDisplayName. Currently, I get the month name with your code. Change that to
return cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
And call it like
public static void main(String[] args) {
System.out.println(getDay("14", "8", "2017"));
}
And I get (as expected)
Monday
In new code, I would prefer the new classes in java.time (Java 8+), and a DateTimeFormatter - like,
public static String getDay(String day, String month, String year) {
int y = Integer.parseInt(year), m = Integer.parseInt(month), d = Integer.parseInt(day);
return java.time.format.DateTimeFormatter.ofPattern("EEEE")
.format(LocalDate.of(y, m, d));
}
java.time.LocalDate
The modern approach uses the java.time classes.
Import java.time.* to access LocalDate & DayOfWeek classes.
Write getDay method which should be static because it is called in main method.
Retrieve localDate by using of method which takes 3 arguments in "int" format.
convert the getDay method arguments in int format.
finally retrieve name of that day using getDayOfWeek method.
There is one video on this challenge.
Java Date and Time Hackerrank
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.of( 2018 , 1 , 23 ) // Pass year-month-day, 1-12 for January-December.
.getDayOfWeek() // Obtain a `DayOfWeek` enum object.
.getDisplayName( // Automatically localize the name of the day-of-week.
TextStyle.FULL , // How long or abbreviated.
Locale.US // Or Locale.CANADA_FRENCH or so on.
) // Returns `String` such as `Monday` or `lundi`.
For Java 6 & 7, see the ThreeTen-Backport project. For earlier Android, see the ThreeTenABP project.
if you want to use LocalDate, you can use it this way
import java.time.LocalDate;
public static String getDay(int month, int day, int year) {
return LocalDate.of(year, month, day).getDayOfWeek().name();
}
public static String getDay(int month, int day, int year) {
String res= java.time.format.DateTimeFormatter.ofPattern("EEEE")
.format(java.time.LocalDate.of(year, month, day));
return res; }
must use java.time.LocalDate, if u will use direct LocalDate its show compile time error i.e cannot find symbol, so plz use java.time.
You can use new Java8 DateTime API.
public static String getDay(int day, int month, int year)
{
LocalDate dt=LocalDate.of(year, month, day);
System.out.println("day: " + dt.getDayOfWeek().toString());
return dt.getDayOfWeek().toString();
}
A LocalDate is a date without time of day, so fine for our purpose. The of factory method constructs the date that we want. Contrary to the Calendar class used in the question it numbers the months sanely from 1 for January through 12 for December. A LocalDate has a getter for day of week. It returns a constant from the DayOfWeek enum whose toString method gives us a nice readable string such as MONDAY, again in contrast to what we get from Calendar.
public static String findDay(int month, int day, int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, (month - 1), day);
String dayOfWeek = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
return dayOfWeek.toUpperCase();
}
Formatting data and time using java.util date and calendar as follows, where it needed to handle an exception with java.text.SimpleDateFormat in java 7.
public static void main(String[] args){
String inputDateStr = String.format("%s/%s/%s", 23, 04, 1995);
Date inputDate = null;
try {
inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
} catch (ParseException ex) {
Logger.getLogger(JavaApplication28.class.getName()).log(Level.SEVERE, null, ex);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(inputDate);
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
System.out.println(dayOfWeek);
}
Formatting date and time using java.time classes in java 8 as follows and it is immutable and thread-safe.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime dateObj = LocalDateTime.now();
System.out.println("Before formatting: " + dateObj);
DateTimeFormatter formatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = dateObj.format(formatObj);
System.out.println("After formatting: " + formattedDate);
}
}
import java.util.GregorianCalendar;
public class CalendarMain {
public static void main(String[] args) {
GregorianCalendar calendar = new GregorianCalendar();
int month = calendar.get(GregorianCalendar.MONTH)+1;
int year = calendar.get(GregorianCalendar.YEAR);
int weekday = calendar.get(GregorianCalendar.DAY_OF_WEEK);
int dayOfMonth = calendar.get(GregorianCalendar.DAY_OF_MONTH);
System.out.println(month+"/"+dayOfMonth+"/"+year);
calendar.add(GregorianCalendar.DAY_OF_MONTH, 10);
System.out.println(GregorianCalendar.DAY_OF_MONTH);
}
}
I am trying to add 10 days to the current date but am getting a weird problem. It does not seem to be adding correctly.
Output:
9/18/2014
5
// Get a calendar which is set to a specified date.
Calendar calendar = new GregorianCalendar(2014, Calendar.JANUARY, 1);
// Get the current date representation of the calendar.
Date startDate = calendar.getTime();
// Increment the calendar's date by 1 day.
calendar.add(Calendar.DAY_OF_MONTH, 1);
// Get the current date representation of the calendar.
Date endDate = calendar.getTime();
System.out.println(startDate);
System.out.println(endDate);
I think the last row is wrong, try this:
System.out.println(calendar.get(GregorianCalendar.DAY_OF_MONTH));
Use
System.out.println(calendar.get(GregorianCalendar.DAY_OF_MONTH));
instead of
System.out.println(GregorianCalendar.DAY_OF_MONTH);
Output :
9/18/2014
28
What you were doing in your code is printing the integer code of GregorianCalendar.DAY_OF_MONTH final variable, Which will remain 5, no matter what you have added in calendar. You were needed to use calendar.get(...) function to get the date of month of this calendar.
All this is my program where i am trying the folowing
Below is my code for Dates functionality...
import java.text.SimpleDateFormat;
import java.util.*;
import java.text.*;
public class DateToCalender {
public static void main(String args[]){
//String strFormat="yyyymmdd";
//DateFormat myDateFormat = new SimpleDateFormat(strFormat);
DateFormat df= new SimpleDateFormat("yyyyMMdd");
df.setLenient(false);
Calendar start=Calendar.getInstance();
try {
Date fromDt =(Date)df.parse("20111207");
//Date myDate = new Date();
//myDate = (Date)myDateFormat.parse("20111207");
//myGDate.setTime(myDate);
start.setTime(fromDt);
start.set(Calendar.MONTH,(start.get(Calendar.MONTH)+1));
System.out.println(start);
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH)-1);
System.out.println(start.get(Calendar.DAY_OF_MONTH));
//System.out.println("From My class"+myGDate.get(Calendar.MONTH));
//System.out.println("From My class new month"+(myGDate.get(Calendar.MONTH)+1));
} catch (ParseException e) {
System.out.println("Invalid Date Parser Exception ");
e.printStackTrace();
}
}
}
when iam executing this code iam getting folowwing o/p
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA
=1,YEAR=2011,MONTH=12,WEEK_OF_YEAR=50,WEEK_OF_MONTH=2,DAY_OF_MONTH=7,DAY_OF_YEAR=341,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=19800000,DST_OFFSET=0]
2011
0
7
**
issue is :
Though iam entering date as 2011/12/07
I am getting year as 2011
month as 0
date as 7
Can some one help in resolving above issue
Could any body please let me know , how this can be resolved .
Don't subtract 1 from the month; Calendar already knows that it's zero-based.
It seems to me like you're doing far too much work here. Why can't you just do this?
private static final DateFormat DEFAULT_DATE_FORMAT;
static {
DEFAULT_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
DEFAULT_DATE_FORMAT.setLenient(false);
}
public Calendar getCalendar(String dateAsString) {
Calendar value = Calendar.getInstance();
Date d = DEFAULT_DATE_FORMAT.parse(dateAsString);
value.setTime(d);
return value;
}
There's an exception that needs to be added to the method signature, but you get the idea. Look at the Calendar javadocs. This could be easier.
setting a condition to check the month can resolve your problem:
try {
Date fromDt =(Date)df.parse("20131209");
start.setTime(fromDt);
start.set(Calendar.MONTH,(start.get(Calendar.MONTH)));
int month = start.get((Calendar.MONTH));
if (month ==11){
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH)+1);
System.out.println(start.get(Calendar.DAY_OF_MONTH));
}else{
start.set(Calendar.MONTH,(start.get(Calendar.MONTH))+1);
System.out.println(start.get(Calendar.YEAR));
System.out.println(start.get(Calendar.MONTH));
System.out.println(start.get(Calendar.DAY_OF_MONTH));
}
}
this will print out :
2013
12
9
What is most convenient and shortest way to get start and end dates of the previous week?
Example: today is 2011-10-12 (input data),but I want to get 2011-10-03 (Monday's date of previous week) and 2011-10-09 (Sunday's date of previous week).
Here's another JodaTime solution. Since you seem to want Dates only (not timestamps), I'd use the DateMidnight class:
final DateTime input = new DateTime();
System.out.println(input);
final DateMidnight startOfLastWeek =
new DateMidnight(input.minusWeeks(1).withDayOfWeek(DateTimeConstants.MONDAY));
System.out.println(startOfLastWeek);
final DateMidnight endOfLastWeek = startOfLastWeek.plusDays(6);
System.out.println(endOfLastWeek);
Output:
2011-10-12T18:13:50.865+02:00
2011-10-03T00:00:00.000+02:00
2011-10-10T00:00:00.000+02:00
public static Calendar firstDayOfLastWeek(Calendar c) {
c = (Calendar) c.clone();
// last week
c.add(Calendar.WEEK_OF_YEAR, -1);
// first day
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
return c;
}
public static Calendar lastDayOfLastWeek(Calendar c) {
c = (Calendar) c.clone();
// first day of this week
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
// last day of previous week
c.add(Calendar.DAY_OF_MONTH, -1);
return c;
}
I would go for #maerics answer if third party library is not involved. I have to replace roll() method with add() method as roll will leave the higher field unchanged. e.g., 22nd August will be obtained from 1st August being rolled -7 days. Note the month remain unchanged.
The source code goes as below.
public static Calendar[] getLastWeekBounds(Calendar c) {
int cdow = c.get(Calendar.DAY_OF_WEEK);
Calendar lastMon = (Calendar) c.clone();
lastMon.add(Calendar.DATE, -7 - (cdow - Calendar.MONDAY));
Calendar lastSun = (Calendar) lastMon.clone();
lastSun.add(Calendar.DATE, 6);
return new Calendar[] { lastMon, lastSun };
}
You can use the Calendar.roll(int,int) method with arguments Calendar.DATE and an offset for the current day of week:
public static Calendar[] getLastWeekBounds(Calendar c) {
int cdow = c.get(Calendar.DAY_OF_WEEK);
Calendar lastMon = (Calendar) c.clone();
lastMon.roll(Calendar.DATE, -7 - (cdow - Calendar.MONDAY));
Calendar lastSun = (Calendar) lastMon.clone();
lastSun.roll(Calendar.DATE, 6);
return new Calendar[] { lastMon, lastSun };
}
This function returns an array of two Calendars, the first being last week's Monday and last week's Sunday.
Wow, the Java date APIs are terrible.
Calendar today = Calendar.getInstance();
Calendar lastWeekSunday = (today.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) ? today.roll(-7): today.roll(Calendar.DAY_OF_YEAR, Calendar.SUNDAY - today.get(Calendar.DAY_OF_WEEK));
Calendar lastWeekMonday = lastWeekSunday.roll( Calendar.DAY_OF_YEAR, -6 );
Using Joda:
DateTime input;
DateTime startOfLastWeek = input.minusWeeks(1).minusDays(input.getDayOfWeek()-1);
DateTime endOfLastWeek = input.minusWeeks(1).plusDays(input.getDayOfWeek()+1);
DateTime endOfLastWeek = startOfLastWeek.plusDays(6);
EDIT:
Joda does not allow a different first day of the week, but strictly sticks to the ISO standard, which states that a week always starts on Monday. However, if you need to make that configurable, you could pass the desired first day of the week as a parameter. See the above link for some other ideas.
public DateTime getFirstDayOfPreviousWeek(DateTime input)
{
return getFirstDayOfPreviousWeek(input, DateTimeConstants.MONDAY);
}
public DateTime getFirstDayOfPreviousWeek(DateTime input, int firstDayOfWeek)
{
return new DateTime(input.minusWeeks(1).withDayOfWeek(firstDayOfWeek));
}
public DateTime getLastDayOfPreviousWeek(DateTime input)
{
return getLastDayOfPreviousWeek(input, DateTimeConstants.MONDAY);
}
public DateTime getLastDayOfPreviousWeek(DateTime input, int firstDayOfWeek)
{
return new DateTime(getFirstDayOfPreviousWeek(input, firstDayOfWeek).plusDays(6));
}
I have two dates
1) from_date: eg. 01/01/2010 (1st January 2010)
2) present_date: eg. 05/06/2011 (5th June 2011)
I want the third date as:
3) req_date: eg. 01/01/2011(1st January 2011)
Year should come from "present_date" and day and month should come from "from_date".
The dates which I mentioned are hardCoded.
In my code, I run a query to get these 2 dates.
Look into the Calendar class
http://www.java-examples.com/add-or-substract-days-current-date-using-java-calendar
Something like // Untested
Calendar cal=Calendar.getInstance();
cal.setTime(from_date);
Calendar cal2=Calendar.getInstance();
cal2.setTime(present_date);
Calendar cal3=Calendar.getInstance();
cal3.set(cal2.get(CALENDAR.YEAR),cal1.get(CALENDAR.MONTH),cal1.get(CALENDAR.DATE));
Date reg_date = cal3.getTime();
You can set individual fields of dates:
Date req_date = from_date;
req_date.setYear (present_date.getYear());
Or, if you're using Calendar (Date is deprecated):
Calendar req_date = from_date;
req_date.set (YEAR, present_date.get(YEAR));
If they're strings, you can just use substringing to get what you want:
String req_date = from_date.substring(0,6) + present_date.substring(6);
(assuming XX/XX/YYYY as seems to be the case).
Not sure if I understand you correctly but this example should get you started:
int year = 2003;
int month = 12;
int day = 12;
String date = year + "/" + month + "/" + day;
java.util.Date utilDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
utilDate = formatter.parse(date);
System.out.println("utilDate:" + utilDate);
} catch (ParseException e) {
System.out.println(e.toString());
e.printStackTrace();
}
this way you can convert date Strings to java.util.Date object, then you can construct the third date by using Date/Calendar methods
from_date: for EX. 01/01/2010 (1 st January 2010)
present_date :for EX. 05/06/2011(5th june 2011)
String s1[]=from_date.split("/");
String s2[]=present_date.split("/");
String newDate=s1[0]+"/"+s1[1]+"/"+s2[2];
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();
System.out.println(date.toString());
}
}