I am trying to get the next Date that match a date format, like getting next Date that match "1 10:00" (format: u HH:mm).
Example: If we are Tuesday June 2 - 22:00 (for example), I want to get Sunday June 7 - 10:00 as a Date object (because it does match "1 10:00" format)
EDIT: It was "u" instead of "F", sorry !
If I understand good your question, this will do the trick. Basically adding 1 minute to current date until you find your desired date by its format.
You'd want to set a safest condition than true.
Calendar calendar = Calendar.getInstance();
Date date = new Date("06/02/2015 10:00");
calendar.setTime(date);
SimpleDateFormat sdf = new SimpleDateFormat("F HH:mm");
while (true) {
calendar.add(Calendar.MINUTE, 1);
if (sdf.format(calendar.getTime()).equals(sdf.format(date))) {
System.out.println(calendar.getTime());
break;
}
}
This prints:
Wed Jun 03 10:00:00 VET 2015 ... and 1440 minutes were added.
I finally found a solution myself :
public static Date getNextDate(SimpleDateFormat format, String value) {
try {
Date date = format.parse(value);
Calendar calendar = Calendar.getInstance();
int diff = date.getDay() - calendar.get(Calendar.DAY_OF_WEEK);
if (!(diff > 0)) {
diff += 7;
}
calendar.add(Calendar.DAY_OF_MONTH, diff);
calendar.set(Calendar.HOUR_OF_DAY, date.getHours());
calendar.set(Calendar.MINUTE, date.getMinutes());
calendar.set(Calendar.MINUTE, date.getSeconds());
return calendar.getTime();
} catch (ParseException exception) {
exception.printStackTrace();
}
return null;
}
It will return the next date that match my format. I use deprecated methods but I will fix it asap.
Thanks for helping anyway !
Related
I have SAS date objects stored as integer and they look like : 19725.
I am trying to write java code to convert the date to YYYY-MM-DD
I see in the documentation that the SAS date value is the number of days from 01 Jan 1960
For example:
02 Jan 1960 would return 1
04 June 2003 would return 15680
Could you give the java code for this conversion. ie. convert something like 19725 to the date format : YYYY-MM-DD
I try the logic below but 15680 gives 2003-01-06 and not 2003-06-04 as the output. Could anyone point the mistake.Thanks in advance.
int numdays = 15680;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 1960);
cal.add(Calendar.DAY_OF_MONTH, numdays);
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
Month are 0-based, so you're setting your calendar to February, not January. This should fix the issue:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, Calendar.JANUARY);
// ...
In addition to RC's point about starting the month correctly with Calendar.JANUARY, your simpledateformat is wrong.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
'DD' is day of year (so 340th day of the year is Dec 6). 'dd' is day of the month. See the doc for more detail. (Also note that 15680 is Dec 6 2002, not what you say in the question.)
You may actually want to use 'yy' also:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
as 'YYYY' is "Week Year", which in some cases may differ from yyyy (calendar year) near the end of the year. See the docs for more details.
I like to use JodaTime for date manipulation like this.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#plusDays-int-
int sasDate = 19725;
DateTime base = new DateTime(1960, 1, 1, 0, 0);
DateTime computed = base.plusDays(sasDate);
I need to convert Monthname + Year to a valid date range. It needs to work with leap years etc.
Examples
getDateRange("Feb",2015)
should find the range 2015-02-01 -- 2015-02-28
While
getDateRange("Feb",2016)
should find the range 2016-02-01 -- 2016-02-29
In Java 8, you can do that using TemporalAdjusters,
LocalDate firstDate= date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDate= date.with(TemporalAdjusters.lastDayOfMonth());
If you have only year and month, it is better to use YearMonth. From YearMonth you can easily get length of that month.
YearMonth ym= YearMonth.of(2015, Month.FEBRUARY);
int monthLen= ym.lengthOfMonth();
Java 8 made Date-Time operations very simple.
For Java 7 and below you could get away with something like this;
void getDate(String month, int year) throws ParseException {
Date start = null, end = null;
//init month and year
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
Date parse = sdf.parse(month);
Calendar instance = Calendar.getInstance();
instance.setTime(parse);
instance.set(Calendar.YEAR, year);
//start is default first day of month
start = instance.getTime();
//calculate end
instance.add(Calendar.MONTH, 1);
instance.add(Calendar.DAY_OF_MONTH, -1);
end = instance.getTime();
System.out.println(start + " " + end);
}
The output would be for "Feb", 2015:
Sun Feb 01 00:00:00 EET 2015
Sat Feb 28 00:00:00 EET 2015
Java 7 solution with default Java tools:
public static void getDateRange(String shortMonth, int year) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
// the parsed date will be the first day of the given month and year
Date startDate = format.parse(shortMonth + " " + year);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
// set calendar to the last day of this given month
calendar.set( Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
// and get a Date object
Date endDate = calendar.getTime();
// do whatever you need to do with your dates, return them in a Pair or print out
System.out.println(startDate);
System.out.println(endDate);
}
Try (untested):
public List<LocalDate> getDateRange(YearMonth yearMonth){
List<LocalDate> dateRange = new ArrayList<>();
IntStream.of(yearMonth.lengthOfMonth()).foreach(day -> dateRange.add(yearMonth.at(day));
return dateRange
}
Java 8 provides new date API as Masud mentioned.
However if you are not working under a Java 8 environment, then lamma date is a good option.
// assuming you know the year and month already. Because every month starts from 1, there should be any problem to create
Date fromDt = new Date(2014, 2, 1);
// build a list containing each date from 2014-02-01 to 2014-02-28
List<Date> dates = Dates.from(fromDt).to(fromDt.lastDayOfMonth()).build();
I am trying to get dates between given two dates and days, for example
date range 20/04/2014 - 210/05/2015
between these dates I am supposed to print dates between Monday to Friday for example. here is the code I developed:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date startDate = (Date) formatter.parse("20/04/2014");
Date endDate = (Date) formatter.parse("10/05/2014");
Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
cal.setTime(startDate);
cal1.setTime(endDate);
while (!cal.equals(cal1)) {
cal.add(Calendar.DATE, 1);
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY|| cal1.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
System.out.println(formatter.format(cal.getTime()));
System.out.println(formatter.format(cal1.getTime()));
}
//System.out.println(formatter.format(cal.getTime()));
}
What I am supposed to see is:
21/04/2014(Monday)
22/04/2014(Tuesday)
23/04/2014(Wednesday)
24/04/2014(Thursday)
25/04/2014(Friday)
28/04/2014(Monday)
29/04/2014(Tuesday)
30/04/2014(Wednesday)
01/05/2014(Thursday)
02/05/2014(Friday)
05/05/2014(Monday)
06/05/2014(Tuesday)
07/05/2014(Wednesday)
08/05/2014(Thursday)
09/05/2014(Friday)
but what I am getting is:
21/04/2014
20/05/2014
28/04/2014
20/05/2014
05/05/2014
20/05/2014
12/05/2014
20/05/2014
19/05/2014
20/05/2014
A few issues
You're reusing the same DateFormat uses to parse the input data String which is missing the required day (E) pattern. Create a separate SimpleDateFormat with pattern dd/MM/yyyy (EEEE) to display the output.
There is only output if the day is Monday or Friday, whereas there should only be output for a weekend day.
Displaying the output for variable cal1 is unnecessary
Example:
while (!calendar1.equals(calendar2)) {
calendar1.add(Calendar.DATE, 1);
if (!(calendar1.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) &&
!calendar2.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)) {
System.out.println(outputFormatter.format(calendar1.getTime()));
}
}
You can use EEEE to print day name..
formatter = new SimpleDateFormat("dd/MM/yyyy(EEEE)");
System.out.println(formatter.format(cal.getTime()));
I know alternate methods to check next date but I would like to know is there any possibility of ignoring checking time when using before.
I have the following code
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
try {
if (fired == true) {
return;
} else {
// first time fired
fired = true;
}
String date = checkDigit(monthOfYear + 1) + "/"
+ checkDigit(dayOfMonth) + "/" + year;
strDate = date;
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date d=df.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
if(d.before(cal.getTime()))
{
etDOB.setText(strDate);
}
else
{
Toast.makeText(context, "Enter Valid Date Of Birth", Toast.LENGTH_SHORT).show();
etDOB.setText(" ");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
d.before(cal.getTime()) checking date but if the selected Date is next Date than it also checking time
Example :
Date value selected is feb 24 2013 so d contains the same
cal.getTime() also contains feb 24 2013
but the first date having the time 00:00:00 GMT+5:30 and second has the time 1:00:00 GMT+5:30 this cause the condition to fail. So my question is how do Ignore before to check time.
You can format and parse the date from cal.getTime() using df (SimpleDateFormat("MM/dd/yyyy")) which will get rid of time and then compare the result with d.
While createing the Calendar Object
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
cal.set(Calendar.Minute, 0);
cal.set(Calendar.Second, 0);
now your condition will not fail
I have a string (Jan12) (generated by applying some operations on current date {20-jan-2012}) Now i want to convert back this string into Date format . Also the value should be same i.e the new Date object should have value jan12 and not (20-jan-2012) . Pls help . I have tried doing
java.sql.Date.valueOf("Jan12") [this throws IllegalArgumentException]
and also
new SimpleDateFormat("MMMyy").parse("Jan12") [By this Date gets converted to 20-jan-2012]
Output required : A Date Object having value Jan12 (12 is the year)
My Code : new java.text.SimpleDateFormat("MMMyy").format(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(s)) // It is a string which gives Jan12
Now i really want to convert Mycode into a Date object
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s1 = df.format(now);
System.out.println(s1); // 2012-01-20
java.sql.Date d111=java.sql.Date.valueOf(s1);
System.out.println(d111); // 2012-01-20
DateFormat df1 = new SimpleDateFormat("MMMyy");
String s2 = df1.format(d111);
System.out.println(s2); //Jan12
Now i want s2 to be converted in Date object
#Aditya,
If you use the Str2 which gives "Jan12", there is no date part in that string and therefore if you convert it to a date object, it will get "Jan" as month, 12 as year but it cant find "day" in that String.
if you use below code
try
{
Date d2 = df1.parse(s2); //here s2 is your string which gives "JAN12"
System.out.println(d2);
}
catch(ParseException pe)
{
System.out.println("parse exception..");
}
The output to the above code will be:
Sun Jan 01 00:00:00 IST 2012
notice here that day part is reset to the first day of the month
Therefore, it is not possible to get a complete date object as your original Date, the month and year are preserved, but the day part is lost.
What do you mean "gets converted"? How your Date is displayed is a separate issue. Look into formatting a Date.
So the 12 is day, not a year - you should parse it as such. Aslo, you'll need to tell it what year this is:
System.out.println(new SimpleDateFormat("yyyyMMMdd").parse("2012" + "Jan12"));
Output
Thu Jan 12 00:00:00 EST 2012
Use the SimpleDateFormat class properly, it will do exactly what you want
String str_date="12-Jan-2012";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse(str_date);
Note: the formatter.parse() method throws ParseException, catch it;
If 12 is a year
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMyy").parse("Jan12"));
calendar.set(Calendar.DATE, 1);
Date date = calendar.getTime(); // First Jan 2012
If 12 is a day
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMdd").parse("Jan12"));
calendar.set(Calendar.YEAR, 2012);
Date date = calendar.getTime(); // 12 Jan 2012
I understand that you want to format your Date object into a String representation.
You can use SimpleDateFormat for this, analog to your second example:
Date d = new Date(112, 0, 20); //don't construct a date like this in production code, use a Calendar instance instead
String formattedDate = new SimpleDateFormat("MMMyy").format(d); // -> "Jan12"
Note that your Date object represents a specific point in time, it will always have a day and a time associated with it.
If you want to compare Dates with the resolution of a month, you have to set day and time to neutral values:
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
d = cal.getTime();
Just extend Date and customize it to use your favourite parse & format methods.