converting a calendar date to a string? - java

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");

Related

Change date from MM/dd to yyyy-MM-dd'T'HH:mm:ss.SSZ in Java

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

JAVA modify date of String format

//Hello all,
So, I have method
public void init() {
list = taskManager.getList();
list.sort((object1, object2) -> ((String) object2.getProperties().get("bpm_startDate"))
.compareTo((String) object1.getProperties().get("bpm_startDate")));
}
This method sorts my list by the date, list gets filled from REST service, so date comes in a String format.
<p:column headerText="#{msg.date}" >
<h:outputText value="#{task.properties.bpm_startDate.substring(0,16).replace('T',' ')}">
</h:outputText>
</p:column>
this is how I "cut-off" all the redundant part of date, before displaying it to the user.
Question is, how to add 3 hours to date ?
you could use java.util.Calendar and DateFormat
//Parse String for Date
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date myDate = format.parse(stringDate);
//Use Calendar to add 3 hours
Calendar c = Calendar.getInstance();
c.setTime(myDate);
c.add(Calendar.HOUR_OF_DAY, 3);
//Retransform date to String
String newDate= format.format(c.getTime());
Remember to replace "yyyy/MM/dd" with your actual format following the official documentation
You can convert String date to Date using SimpleDateFormat like this
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(dateInString);
For adding Hours(time)
Check Calendar class. It has add method (and some others) to allow time manipulation. Something like this should work.
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(date); // sets calendar time/date
cal.add(Calendar.HOUR_OF_DAY, 1); // adds one hour
cal.getTime(); // returns new date object, one hour in the future
I would strongly suggest you check out the Joda-Time library. http://www.joda.org/joda-time/
Since I don't know the format your original date is stored in I can't provide the exact code you want, but you'll need to look at:
DateTimeFormatter - to create a formatter for your strings to a date format. Something like ISODateTimeFormat.dateTimeNoMillis().withZoneUTC() should do the trick. See http://www.joda.org/joda-time/apidocs/index.html
DateTimeFormatter.parseDateTime() - to convert the string to a DateTime
DateTime.plusHours() - see http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#plusHours%28int%29

Calender issue with time zone

I'm having a weird situation with Java Calendar. I'm using dozer mapper to map the objects.
I want to write a method that will convert this object to the following format. yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
say element 2010-11-11T09:30:47.000Z
public Calender getValue(Date source,Calender c) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(source);
return calendar;
}
When I run the program, it is printing
2010-11-11T04:00:47.000Z - Because we are setting the Timezone to be GMT, (9.30 - 5.30 = 4.00)
I want my object to have same format and value.if I don't set TimeZone to GMT, it will show as 2008-11-21T09:30:47.000+05:30.
I want it as 2010-11-11T09:30:47.000Z.
I tried added 5.30 to calender.
calendar.add(Calendar.HOUR, 5);
calendar.add(Calendar.MINUTE, 30)
then it works.But if this is ran from any other place, difference won't be 5.30.So I cannot add 5.30 to calenderget
Is there any way to get rid of this problem? I want to return Calender object.
Any suggestions or help would be much appreciated
Use a pattern. F.E:
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
Also,
SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("yyyyMMdd");
String date_to_string = dateformatyyyyMMdd.format(dateNow);
you can use SimpleDateFormat like this.
SimpleDateFormat formatter, FORMATTER;
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String oldDate = "2011-03-10T11:54:30.207Z";
Date date = formatter.parse(oldDate.substring(0, 24));
FORMATTER = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
System.out.println("OldDate-->"+oldDate);
System.out.println("NewDate-->"+FORMATTER.format(date));
Output OldDate-->2011-03-10T11:54:30.207Z NewDate-->10-Mar-2011 11:54:30.207

Calculating Date in Java

Ok so I am trying to create a date in this format:
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yy");
I am having trouble calculating that date so that it gives me 1/1/13.
Date newdate = new Date (136199001);
String date = dateformat.format(newdate);
However I can't work out how to do it to get to my desired date. I know I am suppose to work it out from 01/01/70 but I am having trouble. The question : what is the formula to work the date out?
I would say that what you are looking for is this:
new SimpleDateFormat("dd/MM/yy").parse("1/1/13");
You can use calendar object for a specific date. It is much easier.
Calendar cal = Calendar.getInstance();
cal.set(2013, 0, 1); //1st january 2013
Date date = cal.getTime();
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yy");
String dateStr = dateformat.format(date);

Adding Years to a random date from Date class

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;

Categories

Resources