Let's say I have this:
PrintStream out = System.out;
Scanner in = new Scanner(System.in);
out.print("Enter a number ... ");
int n = in.nextInt();
I have a random date, for example, 05/06/2015 (it is not a fixed date, it is random every time). If I want to take the 'year' of the this date, and add whatever 'n' is to this year, how do i do that?
None of the methods in the Date Class are 'int'.
And to add years from an int, 'years' has to be an int as well.
You need to convert the Date to a Calendar.
Calendar c = Calendar.getInstance();
c.setTime(randomDate);
c.add(Calendar.YEAR, n);
newDate = c.getTime();
You can manipulate the Year (or other fields) as a Calendar, then convert it back to a Date.
This question has long deserved a modern answer. And even more so after Add 10 years to current date in Java 8 has been deemed a duplicate of this question.
The other answers were fine answers in 2012. The years have moved on, today I believe that no one should use the now outdated classes Calendar and Date, not to mention SimpleDateFormat. The modern Java date and time API is so much nicer to work with.
Using the example from that duplicate question, first we need
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
With this we can do:
String currentDateString = "2017-09-12 00:00:00";
LocalDateTime dateTime = LocalDateTime.parse(currentDateString, formatter);
dateTime = dateTime.plusYears(10);
String tenYearsAfterString = dateTime.format(formatter);
System.out.println(tenYearsAfterString);
This prints:
2027-09-12 00:00:00
If you don’t need the time of day, I recommend the LocalDate class instead of LocalDateTime since it is exactly a date without time of day.
LocalDate date = dateTime.toLocalDate();
date = date.plusYears(10);
The result is a date of 2027-09-12.
Question: where can I learn to use the modern API?
You may start with the Oracle tutorial. There’s much more material on the net, go search.
Another package for doing this exists in org.apache.commons.lang3.time, DateUtils.
Date date = new Date();
date = DateUtils.addYears(date, int quantity = 1);
The Date class will not help you, but the Calendar class can:
Calendar cal = Calendar.getInstance();
Date f;
...
cal.setTime(f);
cal.add(Calendar.YEAR, n); // Where n is int
f = cal.getTime();
Notice that you still have to assign a value to the f variable. I frequently use SimpleDateFormat to convert strings to dates.
Hope this helps you.
Try java.util.Calendar type.
Calendar cal=Calendar.getInstance();
cal.setTime(yourDate.getTime());
cal.set(Calendar.YEAR,n);
This will add 3 years to the current date and print the year.
System.out.println(LocalDate.now().plusYears(3).getYear());
If you need add one year a any date use the object Calendar.
Calendar dateMoreOneYear = Calendar.getInstance();
dateMoreOneYear.setTime(dateOriginal);
dateMoreOneYear.add(Calendar.DAY_OF_MONTH, 365);
Try like this as well for a just month and year like (June 2019)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, n); //here n is no.of year you want to increase
SimpleDateFormat format1 = new SimpleDateFormat("MMM YYYY");
System.out.println(cal.getTime());
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
Try this....
String s = new SimpleDateFormat("YYYY").format(new Date(random_date_in_long)); //
int i = Integer.parseInt(s)+n;
Related
I have a String that formatted MM/dd. I would like to convert it to a Date in format yyyy-MM-dd'T'HH:mm:ss.SSZ.
DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = "06/05";
Date date = new Date();
date = df.parse(strDate);
This makes it a Date, but in the original format.
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSZ").format(date));
This returns the correct month and day, but nopthing else.
1970-06-05T00:00:00.00-0400
Any idea how I can make it return
CURRENT_YEAR-06-05TCURRENT_TIME
In the question, the date format pattern indicates a desire for 2-digit fractional seconds. SimpleDateFormat cannot do that.
The newer Java 8 Time API can, and you should be using that anyway.
If you're running on Java 6 or 7, get the ThreeTen-Backport library.
To parse a MM/dd formatted string and get a full timestamp with current year and time-of-day, in the default time zone, use the following code:
String strDate = "06/05";
MonthDay monthDay = MonthDay.parse(strDate, DateTimeFormatter.ofPattern("MM/dd"));
ZonedDateTime date = ZonedDateTime.now().with(monthDay);
System.out.println(date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSZ")));
Sample Output
2020-06-05T14:52:48.45-0400
I recommend to make use of java.time package. There you go:
var ds = "01/12";
var df = java.time.format.DateTimeFormatter.ofPattern("MM/dd");
var dt = java.time.MonthDay.from(df.parse(ds)).adjustInto(java.time.LocalDateTime.now());
Then you can convert dt to java.util.Date or whatever you like. Or simply use one of java.time formaters to get the desired output.
You are creating a date with only month and day
If you want to use the current year and time, you can create a calendar object and edit the month and day
For something this simple I suggest a different approach, get current time then set month and day from the original string THEN format.
String str = "08/09";
String[] split = str.split("/");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Integer.parseInt(split[0]));
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(split[1]));
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(calendar.getTime()));
String strDate = "06-05";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-"+strDate+"'T'HH:mm:ss.SSZ");
System.out.println(sdf.format(new Date()));
the output:
2020-06-05T23:00:45.306+0400
I am facing issue like I have a datasheet which have a string value like 123459 which is a time and I have another column where I am adding in value as plus 5 seconds.
When I am adding value its add as 123464 instead of 123504.
Could anyone help me to resolve this?
Use the java.time classes built into Java 8 and later. See Oracle Tutorial.
Specifically, the LocalTime and DateTimeFormatter classes.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
LocalTime localTime = LocalTime.parse("123459", formatter);
LocalTime timeIn5Seconds = localTime.plusSeconds(5);
System.out.println(timeIn5Seconds.format(formatter));
Output
123504
to convert string to date format...
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(str);
to add 5 seconds
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(date); // sets calendar time/date according to the OBJECT
cal.add(Calendar.SECOND, 5); // adds 5 SECONDS
cal.getTime();
I have a date stored in a String field in SQLITE with the String value
"/Date(1411472160000+0100)/"
how can I convert this back into a date format , the code below doesn't work. I think I need to convert from the milliseconds first but I cant see how to even get the above text into a long format first ?
any suggestions ?
Date convertedDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm",
java.util.Locale.getDefault());
convertedDate = dateFormat.parse(dateString);
return dateFormat.format(convertedDate);
Well, a substring from the indexOf("(") to the indexOf("+") and you should find the date in milli.
From there, I believe you can find the date ;)
String s = "/Date(1411472160000+0100)/";
s = s.substring(s.indexOf("(") + 1, s.indexOf("+"));
Date d = new Date(Long.parseLong(s));
With the same structure, you can find the timezone (+0100) (from "+" to ")") and work with a Calendar to find the right time for the right time area.
First you have to parse out the time value from String i.e. "1411472160000+0100" part.
Here in "1411472160000+0100" , "+0100" is the timezone info. If you don't want to consider the timezone, then you can take following approach.
Approach-1
long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);
int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
then to get the date in your specified format you can use-
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25
Besides this approach, there is an excellent Java Date library called JodaTime.
If you want to incorporate the timezone info , you can refer to this constructor from JodaTime.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#DateTime-long-org.joda.time.DateTimeZone-
Given a String that is simply a day, for example, "Thu" or "Thursday", how would I get a java.util.Calendar object where the day String represents the closest String to today. In other words, today is Monday, 3/26/29012, so if the String were "Thu", I would want to form a date that represents "3/29/2012". If the String passed in is "Mon" and we're on Monday, I would want today's date. In this example, "3/26/2012".
I tried this ...
final DateFormat formatter = new SimpleDateFormat("EEE");
java.util.Date date = (Date) formatter.parse(dayOfWeekStr);
final Calendar now = Calendar.getInstance();
dateCal.set(Calendar.YEAR, now.get(Calendar.YEAR));
dateCal.set(Calendar.MONTH, now.get(Calendar.MONTH));
dateCal.setTime(date);
but it isn't working. Once I set the date, the year and month results to 1970, January.
You are almost there. Just put .setTime(..) ontop of the rest. Currently you are overriding your YEAR and MONTH changes by setting the time.
As Kevin noted, it might not work in all cases. For that reason I'd suggest you use a different approach: get only the DAY_OF_WEEK from a calendar, based on the parsed date, and set it to now. Of course, you should take care of changing the week if you need to.
I ended up going with
public static Calendar getNearestDateFromDayString(final String dayOfWeekStr,
final Calendar startingDay) throws ParseException {
final DateFormat formatter = new SimpleDateFormat("EEE");
final java.util.Date date = (Date) formatter.parse(dayOfWeekStr);
final Calendar result = Calendar.getInstance();
result.setTime(date);
result.set(Calendar.YEAR, startingDay.get(Calendar.YEAR));
result.set(Calendar.MONTH, startingDay.get(Calendar.MONTH));
result.set(Calendar.HOUR, startingDay.get(Calendar.HOUR));
result.set(Calendar.MINUTE, startingDay.get(Calendar.MINUTE));
result.set(Calendar.SECOND, 0);
java.util.Date today = new java.util.Date();
while (result.getTimeInMillis() <= today.getTime()) {
result.add(Calendar.DATE, 7);
} // while
return result;
} // getNearestDateFromDayString
If anyone has a more concise solution, I'll accept that instead.
I am trying to get the program to call up the current date, add 30 days to it, and then out put that date as a string.
// Set calendar for due date on invoice gui
Calendar cal = Calendar.getInstance();
// Add 30 days to the calendar for the due date
cal.add(Calendar.DATE, 30);
Date dueDate = cal.getTime();
dueDatestr = Calendar.toString(dueDate);
And the question is?
If you want to format your date, I suggest looking at java.text.SimpleDateFormat instead of using toString(). You can do something like:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
dueDateStr = dateFormat.format(dueDate); // renders as 11/29/2009
You almost have it:
Date dueDate = cal.getTime();
String dueDateAsString = dueDate.toString();
or
String dueDateAsFormattedString = DateFormat.format(dueDate);
You might want to consider using FastDateFormat from Apache commons, instead of SimpleDateFormat, because SimpleDateFormat is not thread safe.
FastDateFormat dateFormat = FastDateFormat.getInstance("MM/dd/yyyy");
dueDateStr = dateFormat.format(dueDate);
This is especially true if you wanted to use a static instance of the date formatter, which is a common temptation.
You can do it easily with a class of mine:
https://github.com/knyttl/Maite/wiki/Maite-Date-and-Time
new Time()
.plus(1, Time.DAY)
.format("yyyy-MM-dd");