Date function in java - java

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

Related

Calculate no of days between two dates in java [duplicate]

This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);

Finding week number by passing two timestamps as parameter in Java [duplicate]

This question already has answers here:
Get the number of weeks between two Dates.
(19 answers)
Closed 6 years ago.
My function should take start timestamp, end timestamp and entered date. Here, start and end timestamps could be anything (any timestamp).
This start timestamp and end timestamp will be of three week. If entered date falls in those timestamp range I need to get week of that date.
example:
start date - 06/08/2011 00:00:00
end Date - 26/08/2011 00:00:00
if entered date - 10/08/2011 This should return week number as 1
if entered date - 27/08/2011 This should return week number as 3.it has to take count of 7 days,from entered date and give the count of week.
Below is my code used.
import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class LocaleTimeSample {
public static void main(String... args) {
try {
String dt = "";
String dt1 = "";
String dt2 = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
sdf.setLenient(false);
String givenDateString = "02/06/2016";// given
String startDateString = "01/06/2016";// start
String endDateString = "21/06/2016";// end
Date givenDate = sdf.parse(givenDateString);
Date startDate = sdf.parse(startDateString);
Date endDate = sdf.parse(endDateString);
try {
c.setTime(sdf.parse(startDateString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("1 Week Date : " + dt);
Date date1 = (Date) sdf.parse(dt);
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt1 = sdf.format(c.getTime());
System.out.println("2 Week Date : " + dt1);
Date date2 = (Date) sdf.parse(dt1);
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt2 = sdf.format(c.getTime());
System.out.println("2 Week Date : " + dt2);
Date date3 = (Date) sdf.parse(dt2);
if (givenDate.compareTo(date1) <= 0) {
System.out.println("Week 1");
} else if (givenDate.compareTo(date2) <= 0
&& givenDate.compareTo(date1) > 0) {
System.out.println("Week 2");
} else if (givenDate.compareTo(date3) <= 0
&& givenDate.compareTo(date2) > 0) {
System.out.println("Week 3");
}
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
Can anybody help me to minimixe the code of line and reusability apprach where were needed.
Any idea regarding this is appreciated.
Convert to Date or Calendar and retreive the field you need
Assumming your Date is String this is what you must do to convert it to Date and Calendar
String startDate = "06/08/2011 00:00:00";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date startDateasDate = format.parse(startDate);
Calendar cal = Calendar.getInstance();
cal.setTime(startDateasDate);
Then you can retrieve wichever date you want with the proper flag:
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
Here you can see a list of the available flags:
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
Convert the start date, end date and input date to LocalDateTime
Check that the entered date is after the start date and before the end date. You can use LocalDateTime.isBefore and isAfter for this.
Use LocalDateTime.until with TemporalUnit set to weeks to calculate the amount of weeks from the start date to the entered date. You can then add 1 to this result to get the week number (0 amount of weeks = week 1, 1 amount of weeks = week 2 and so on)

I want my string to converted to a day [duplicate]

This question already has answers here:
How to determine day of week by passing specific date?
(28 answers)
Closed 7 years ago.
I have this string
String s = "29/04/2015"
And I want it to produce the name of that day in my language, which is Norwegian.
For example:
29/04/2015 is "Onsdag"
30/04/2015 is "Torsdag"
How can I do this?
String dateString = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat("E", Locale.no_NO);
String day = formatter.format(date);
Now day will have the day in given locale. Update
You need to configure an instance of DateFormat, with your locale, (take a look at https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html).
then parse the Date and get the day, as Dilip already suggests.
You can use date parsing combined with Locale settings to get the desired output. For e.g. refer following code.
String dateStr = "29/04/2015";
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date dt = dtf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
String m = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG_FORMAT, new Locale("no", "NO"));
System.out.println(m);
For more information about locale, visit Oracle Java Documentation.
First you will need to parse the String to a Date. Then use a Calendar to get the day of the week. You can use an array to convert it to the appropriate string.
// Array of Days
final String[] DAYS = {
"søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"
};
// Parse the date
final String source = "27/04/2015";
final DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {
date = format.parse(source);
} catch (final ParseException e) {
e.printStackTrace();
}
// Convert to calendar
final Calendar c = Calendar.getInstance();
c.setTime(date);
final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
// Get the day's name
System.out.println("Day of Week: " + dayOfWeek);
System.out.println("Day = " + DAYS[dayOfWeek - 1]);
You need to parse your text with date to Date instance and then format it back to text. You can do it with SimpleDateFormat class which supports many patterns of dates like
dd/MM/yyyy for your original date,
and EEEE for full name of day in month.
While formatting you will also need to specify locale you want to use. To create Norway specific locale you can use for instance
Locale nor = Locale.forLanguageTag("no-NO");
So your code can look more or less like:
String text = "29/04/2015";
Locale nor = Locale.forLanguageTag("no-NO");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", nor);
SimpleDateFormat dayOfWeek = new SimpleDateFormat("EEEE", nor);
Date date = sdf.parse(text);
System.out.println(dayOfWeek.format(date));
Output: onsdag.
final int SUNDAY = 1;
final int ONSDAG = 2;
final int TORSDAG = 3;
....
....
String s = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(s);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
String dayString;
switch (day) {
case(ONSDAG):
dayString = "ONSDAG";
break;
....
}
EDIT: I just tested this and it actually starts from Sunday, and returns the value of 1 for sunday, I've changed the constant values to reflect this.
First you'll need a Calendar object.
Calendar cal = Calendar.getInstance();
String s = "29/04/2015"
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
cal.setTime(format.parse(s));
From the Calendar you can get the day of the week.
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
dayOfWeek will be 1-7 with Sunday (in english) being 1
You can use an HashMap map where the first parametri is the date "29/4/2015" while the second is the meaning. You can use your string to get the meaning map.get (yourString).

Using Java SimpleDateFormat to find max date

I haven't programmed in Java for many years, but I now have to change a program I wrote some time ago. In this program I need to read a QIF file and find the qif record with the maximum date (Dmm-dd-yyyy).
I could not get this to work in my program so I wrote a simple test to demonstrate the problem I am having. I think there are other ways to do this, like lists and collections. But I still want to know why using SimpleDateFormat won't work. Notice in the output that this method produces the max for July but seems to ignore all August dates.
Thanks, Mike
import java.text.SimpleDateFormat;
import java.util.Date;
class DateParser {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
Date nextDate = null;
Date maxDate = null;
String nextStrDate = null;
String maxStrDate = null;
//Fill date array.
String date[] = {"07-14-2014","07-22-2014","07-31-2014",
"08-01-2014","08-04-2014","08-06-2014"};
try {
//Start with early maximum date.
maxDate = sdf.parse("01-01-1800");
// Find Max date in array.
for (int i=0; i<6; ++i) {
nextStrDate = date[i];
nextDate = sdf.parse(nextStrDate);
if(nextDate.after(maxDate)){
maxStrDate = nextStrDate;
maxDate = nextDate;
}
System.out.println( "Next Date = " + nextStrDate);
}
System.out.println("\nMax Date = " + maxStrDate);
} catch (Exception e) {
System.out.println("Got error:" + e);
}
}
}
OUTPUT
Next Date = 07-14-2014
Next Date = 07-22-2014
Next Date = 07-31-2014
Next Date = 08-01-2014
Next Date = 08-04-2014
Next Date = 08-06-2014
Max Date = 07-31-2014
From the Java Docs....
m Minute in hour
What you want is
M Month in year
Change mm-dd-yyyy to MM-dd-yyyy
You format is incorrect, this
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
should be
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
because (per the SimpleDateFormat documentation),
Letter Date or Time Component Presentation Examples
...
M Month in year Month July; Jul; 07
...
m Minute in hour Number 30

get the right Month format date java

can any help, how to get the right date from an String like this "2014-01-10T09:41:16.000+0000"
my code is:
String strDate = "2014-01-10T09:41:16.000+0000";
String day = "";
String format = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
Locale locale = new Locale("es", "ES");
SimpleDateFormat formater = new SimpleDateFormat(format, locale);
formater.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
Calendar cal = Calendar.getInstance();
try {
cal.setTimeInMillis(formater.parse(strDate).getTime());
String offerDate = cal.get(Calendar.DAY_OF_MONTH) + "-" + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.YEAR);
System.out.println(offerDate);
} catch (Exception e){
System.out.println(e.getMessage());
}
in the result i give something like this: "10-0-2014", i want the result like that "10-01-2014"
thanks in advance :)
The documentation states:
java.util.Calendar.MONTH
MONTH public static final int MONTH Field number for get and set
indicating the month. This is a calendar-specific value. The first
month of the year in the Gregorian and Julian calendars is JANUARY
which is 0; the last depends on the number of months in a year.
-> Counting starts at 0 for Calendar.MONTH
I think the easiest would be to use another formatter object to do the formatting instead of building it yourself:
try {
Date d = new Date(cal.setTimeInMillis(formater.parse(strDate).getTime()));
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String offerDate = format.format(d);
System.out.println(offerDate);
} catch (Exception e){
System.out.println(e.getMessage());
}

Categories

Resources