JAVA modify date of String format - java

//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

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

Adding 30 days on the value from JDateChooser using Java netbeans

hi all I am working on a form using JDateChooser I want to get the value of date inputted by the user. Is there any ways that after storing the value of date in a variable can I add 30 days from the inputted date? This is my code in passing the date to a string variable:
String dates =((JTextField)date.getDateEditor().getUiComponent()).getText();
my problem is how can I pass the date into a variable where i can be able to add an additional 30 days on it?
please help me really need this for my project .
To manipulate a String with a date value, you first need to convert to a Date using SimpleDateFormat, then you can perform manipulation using a Calendar.
SimpleDateFormat datefmt = new SimpleDateFormat("MM/dd/yyyy"); // Or format you're using
Date date = datefmt.parse(dates);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 30); // Add 30 days
Date futureDate = cal.getTime();
If you need value for insertion into a database, you will of course use PreparedStatement, so you'll need a Timestamp instead:
// From Date
Timestamp futureTimestamp = new Timestamp(futureDate.getTime());
// Directly from Calendar
Timestamp futureTimestamp = new Timestamp(cal.getTimeInMillis());

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

Convert Calendar to XMLGregorianCalendar with specific formatting

I am having some issues in converting a calendar object to an XMLGregorian calendar in the format of YYYY-MM-DD HH:mm:ss.
My current code is:
Calendar createDate = tRow.getBasic().getDateCreated(0).getSearchValue();
Date cDate = createDate.getTime();
GregorianCalendar c = new GregorianCalendar();
c.setTime(cDate);
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
which returns a date of 2013-01-03T11:50:00.000-05:00.
I would like it to read 2013-01-03 11:50:00.
I have checked a bunch of posts, which use DateFormat to parse a string representation of the date, however my dates are provided to me as a Calendar object, not a string.
I'd appreciate a nudge in the right direction to help me figure this one out.
An XMLGregorianCalendar has a specific W3C string representation that you cannot change.
However, you can format a Date with SimpleDateFormat.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = dateFormat.format(cDate);
You can get a Date object from a XMLGregorianCalendar object as follows:
xmlCalendar.getGregorianCalendar().getDate()
DateFormat#format takes a Object parameter. From memory, it should accept a Calendar object, if not, it WILL accept a Date object, so you could use Calendar#getTime as a worse case scenario
You can use a instance of SimpleDateFormat to specify a custom formatting. This will ensure that the result is always the same for different systems
Have you seen this tutorial it may help?
http://www.vogella.com/articles/JavaDateTimeAPI/article.html
Speicifcally this code is a good example:
// Format the output with leading zeros for days and month
SimpleDateFormat date_format = new SimpleDateFormat("yyyyMMdd");
System.out.println(date_format.format(cal1.getTime()));

converting a calendar date to a string?

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

Categories

Resources