why use different date format makes different result in same date? - java

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

Related

How to do subtraction from a particular date using Java [duplicate]

This question already has answers here:
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 4 years ago.
I am encountering an issue which is related to Java Date Function.
I'm getting the date from Application (example: 6/5/18) which is in MM/DD/YY format. Now I need to do -2 from the date. I know how to do -2 from current system date using calendar object (see the below code).
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
info("Date is displayed as : "+ PastDate );
I'm not able to put the date which I'm getting from Application in this format. Can someone please help me? (Any other way to do it would also be fine)
I suggest you to use Java 8 compatible Date and Time types.
If you use java.time.LocalDate then this is the solution:
LocalDate.now().minusDays(2)
From your question, it seems that you have the challenge in dealing with formatting, and then doing the subtraction.
I would recommend Java Date and Time Apis for this purpose, using a formatter.
A junit method to achieve your requirement is given below
#Test
public void testDateFormatUsingJava8() {
CharSequence inputdateTxt = "6/5/18";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate inputDate = LocalDate.parse(inputdateTxt, formatter);
System.out.println(inputDate.minusDays(2L).format(formatter));
}
#Test
public void testDateCalenderUsingStringSplit() {
String inputdateTxt = "6/5/18";
String[] dateComponenets = inputdateTxt.split("//");
Calendar cal = Calendar.getInstance();
//Know where are the year month and date are stored.
cal.set(Integer.parseInt(dateComponenets[2]), Integer.parseInt(dateComponenets[0]), Integer.parseInt(dateComponenets[2]) );
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
}
#Test
public void testDateCalenderUsingJavaUtilDateApi() throws ParseException {
String inputdateTxt = "6/5/18";
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
Date date = dateFormat.parse(inputdateTxt);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE,-2);
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
The reason why I use "M/d/yy" is because your question does not pad the date and month fields in the input date with a zero. If there is a guarantee that you receive a padded value in the date and month field, using "MM/dd/yy" is suggested.
See the following answer for your reference :
DateTimeFormatterSupport for Single Digit Values
EDIT: considering the limitation to not use Java 8 Date Time APIs, I have added two other alternatives to solve the problem. The OP is free to choose any one of the solutions. Kept the Java 8 solution intact for information purposes.
Calendar cal = Calendar.getInstance();
cal.set(2018, 5, 6); // add this, setting data from the value you parsed
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ PastDate);

increment now date by several days issue in java [duplicate]

This question already has answers here:
how to add days to java simple date format
(2 answers)
Closed 8 years ago.
I need to increment date by some days.
private Date now = new Date();
private Date result;
public void incrementDate(Integer days) {
result =
}
So if days equals 3 i need to increment my now date on 3 days and set it to result.
I know that java 8 has plusDays method in LocalDate class. Is there a way how to implement this in java 7.
Use Calendar
Calendar cal = Calendar.getInstance ();
cal.setTime (now);
cal.add (Calendar.DATE, days);
plus other fun stuff.
Use Calendar to do this:
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DATE,3);
result = cal.getTime()
I suggest you make the function static and pass in now. return Date and use a Calendar. Something like,
public static Date incrementDate(Date now, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(now);
cal.add(Calendar.DAY_OF_MONTH, days);
return cal.getTime();
}
And then to test it
public static void main(String[] args) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date now = new Date();
System.out.println(df.format(now));
System.out.println(df.format(incrementDate(now, 3)));
}
Output here (today) is
2014-11-12
2014-11-15
try this code :
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
Calendar cal=Calendar.getInstance();
String today=sdf.format(cal.getTime());
System.out.println(today);
cal.add(Calendar.DATE, 20);
String After=sdf.format(cal.getTime());
System.out.println(After);
Date now = new Date();

Android: Java SimpleDateFormat: Why February is March?

I can't resolve this question.
I wrote this code:
public static String getMonthName(int year, int month, int day){
Locale locale = Locale.getDefault();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM",locale);
Date date = new Date();
date.setDate(day);
date.setMonth(month);
date.setYear(year);
return sdf.format(date);
}
It works very well but when month = 1 (that is February), month name is March and not February! Why?
This code works very well for all other days and months...
There is another way to get translated month name?
Please help me....
Depending on how you call your function (eg using current day as the 29 of Feb which doesn't exist in 2013), you may make the month being incremented automatically.
I'd suggest the use of this function which avoids the problem :
public static String getMonthName(int month){
Locale locale = Locale.getDefault();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM",locale);
Date date = new Date();
date.setDate(1);
date.setMonth(month);
date.setYear(2012);
return sdf.format(date);
}
This is because the months start from zero index, So you should use this logic
if(day >0)
{
day =day -1;
}

Formatting date and time

I have a question related to conversion/formatting of date.
I have a date,say,workDate with a value, eg: 2011-11-27 00:00:00
From an input textbox, I receive a time value(as String) in the form "HH:mm:ss", eg: "06:00:00"
My task is to create a new Date,say,newWorkDate, having the same year,month,date as workDate,and time to be the textbox input value.
So in this case, newWorkDate should be equal to 2011-11-27 06:00:00.
Can you help me figure out how this can be achieved using Java?
Here is what I have so far:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
//Text box input is converted to Date format -what will be the default year,month and date set here?
Date textBoxTime = df.parse(minorMandatoryShiftStartTimeStr);
Date workDate = getWorkDate();
int year = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(0, 4));
int month = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(4, 6));
int date = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(6, 8));
Date newWorkDate = DateHelper.createDate(year, month, day);
//not sure how to set the textBox time to this newWorkDate.
[UPDATE]: Thx for the help,guys!Here is the updated code based on all your suggestions..Hopefully this will work.:)
String[] split = textBoxTime.split(":");
int hour = 0;
if (!split[0].isEmpty)){
hour = Integer.parseInt(split[0]);}
int minute = 0;
if (!split[1].isEmpty()){
minute = Integer.parseInt(split[1]);}
int second = 0;
if (!split[2].isEmpty()){
second = Integer.parseInt(split[2]);}
Calendar cal=Calendar.getInstance();
cal.setTime(workDate);
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
Date newWorkDate = cal.getTime();
A couple of hints:
Use a Calendar object to work with the dates. You can set the Calendar from a Date so the way you create the dates textBoxTime and workDate are fine.
Set the values of workDate from textBoxTime using the setXXX methods on Calendar class (make workDate a Calendar)
You can use SimpleDateFormat to format as well as parse. Use this to produce the desired output.
You should be able to do this with no string parsing and just a few lines of code.
Since you already have the work date, all you need to do is convert your timebox to seconds and add it to your date object.
Use Calendar for date Arithmetic.
Calendar cal=Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, hour);
cal.add(Calendar.MINUTE, minute);
cal.add(Calendar.SECOND, second);
Date desiredDate = cal.getTime();
You may need the following code.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateFormat {
public static void main(String[] args) {
try {
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date workDate = simpleDateFormat1.parse("2011-11-27");
Calendar workCalendar= Calendar.getInstance();
workCalendar.setTime(workDate);
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH:mm:ss");
Calendar time = Calendar.getInstance();
time.setTime(simpleDateFormat2.parse("06:00:00"));
workCalendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
workCalendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
workCalendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
Date newWorkDate = workCalendar.getTime();
SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
System.out.println(simpleDateFormat3.format(newWorkDate));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hope this would help you.

Julian Date Conversion

Sample Julian Dates:
2009218
2009225
2009243
How do I convert them into a regular date?
I tried converting them using online converter and I got-
12-13-7359 for 2009225!! Makes no sense!
Use the Joda-Time library and do something like this:
String dateStr = "2009218";
MutableDateTime mdt = new MutableDateTime();
mdt.setYear(Integer.parseInt(dateStr.subString(0,3)));
mdt.setDayOfYear(Integer.parseInt(dateStr.subString(4)));
Date parsedDate = mdt.toDate();
Using the Java API:
String dateStr = "2009218";
Calendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR,Integer.parseInt(dateStr.subString(0,3)));
cal.set(Calendar.DAY_OF_YEAR,Integer.parseInt(dateStr.subString(4)));
Date parsedDate = cal.getTime();
---- EDIT ----
Thanks for Alex for providing the best answer:
Date myDate = new SimpleDateFormat("yyyyD").parse("2009218")
Another format is CYYDDDD I wrote this function in Java
public static int convertToJulian(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
String syear = String.format("%04d",year).substring(2);
int century = Integer.parseInt(String.valueOf(((year / 100)+1)).substring(1));
int julian = Integer.parseInt(String.format("%d%s%03d",century,syear,calendar.get(Calendar.DAY_OF_YEAR)));
return julian;
}

Categories