How to Convert string to xml gregorian calendar date java - java

I am trying to convert String to gregoriancalendar date, it unable to convert. because, the string has different format. like '2015-05-22T16:28:40.317-04:00'. I have seen some of the other examples, but they are not in this time format.
I am using something like below:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-SS:zz").parse(sampleDate));
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);
I even tried like this too:
gregory.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(sampleDate));

If you check SimpleDateFormat doc, you will see that there's no T in the format pattern. In order to escape non-pattern characters, wrap them around single quotes ' as shown in this example (taken from the docs):
"hh 'o''clock' a, zzzz" -> 12 o'clock PM, Pacific Daylight Time
I think the proper format should be this:
String format = "yyyy-MM-dd'T'HH:mm:ss.SSSX";
// ^-^-----check these
// don't pay attention to the smiley generated above, they're arrows ;)
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new SimpleDateFormat(format).parse(sampleDate));
XMLGregorianCalendar calendar = DatatypeFactory.newInstance().newXMLGregorianCalendar( cal);

This works as well
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar("2015-05-22T16:28:40.317-04:00");
GregorianCalendar gregorianCalendar = xmlGregorianCalendar.toGregorianCalendar();

try {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss-SS:zz");
//dateFormat.setTimeZone(TimeZone.getTimeZone());
Date inputDate = dateFormat.parse(inputDatetime);
GregorianCalendar c = new GregorianCalendar();
c.setTime(inputDate);
XMLGregorianCalendar outputDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
return outputDate;
} catch (ParseException | DatatypeConfigurationException e) {
log.error("exception: {}", e.getMessage());
return null;
}

Related

Changing date formats

I have the following code:
// OLD DATE
String date = "Mon, 06/07";
DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = date.substring(date.length() - 5);
Date dateOld;
try {
dateOld = df.parse(strDate);
} catch (Exception e) {
e.printStackTrace();
}
String dateStr = df.format(dateOld);
MonthDay monthDay = MonthDay.parse(dateStr, DateTimeFormatter.ofPattern("MM/dd"));
ZonedDateTime dateNew = ZonedDateTime.now().with(monthDay);
// NEW DATE
System.out.println(dateNew.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T00:00:00Z'")));
Basically what I am trying to do is change Mon, 06/07 format to this format 2021-06-07T00:00:00Z.
What I have works, but it is really terrible. What would be a better way of doing it?
This is a little tricky as you need to make some assumptions
The year, as it's not specified in the original format
TimeZone, as it's not specified at all (the final output seems to point to UTC)
The first thing your need to do, is parse the String input into a LocalDate (you could just go straight to ZonedDate, but this is where I started)
String date = "Mon, 06/07";
DateTimeFormatter parseFormatter = new DateTimeFormatterBuilder()
.appendPattern("E, M/d")
.parseDefaulting(ChronoField.YEAR, 2021)
.toFormatter(Locale.US);
LocalDate ld = LocalDate.parse(date, parseFormatter);
Then you need to convert that to LocalDateTime
LocalDateTime ldt = ld.atStartOfDay();
And then, to a ZonedDateTime. Here' I've assumed UTC
//ZoneId zoneId = ZoneId.systemDefault();
//ZonedDateTime zdt = ldt.atZone(zoneId);
OffsetDateTime zdt = ldt.atOffset(ZoneOffset.UTC);
And finally, format the result to your desired format
String formatted = zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(formatted);
Which, for me, prints...
2021-06-07T00:00:00Z
A lot of time and effort has gone into the new Date/Time APIs and you should make the time to try and learn them as best you can (I'm pretty rusty, but with a little tinkering, got to a result)
Maybe start with Date/Time trails
A solution use Calendar, Date and SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MM/dd", Locale.getDefault());
try {
Date oldDate = sdf.parse("Mon, 06/07");
Calendar calendar = Calendar.getInstance();
int savedYear = calendar.get(Calendar.YEAR);
if (oldDate != null) {
calendar.setTime(oldDate);
calendar.set(Calendar.YEAR, savedYear);
sdf.applyPattern("yyyy-MM-dd'T00:00:00Z'");
System.out.println(sdf.format(calendar.getTime()));
}
} catch (ParseException e) {
e.printStackTrace();
}

Java Get One Day Before Specific Date

I have a String expired date. But I need to perform some SQL statement the day before expired date falls. I get my expired date and by:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String expiredDate = null;
String currentDate = dateFormat.format(new Date());
Calendar cal = Calendar.getInstance();
try {
cal.setTime(dateFormat.parse(loanDate));
cal.add(Calendar.WEEK_OF_YEAR, 2);
expiredDate = dateFormat.format(cal.getTimeInMillis());
cal.add(Calendar.WEEK_OF_YEAR, -2);
} catch (ParseException e) {
e.printStackTrace();
}
Then, I got an if statement to perform SQL statement:
if(expiredDate.equals(currentDate)){
promptExtensionDialog();
}
What I am trying to achieve is for the if statement, instead of the expiredDate itself, I need to get one day before the expired date and compare with the current date. I wonder how to achieve this?
Thanks in advance.
EDIT
try {
cal.setTime(dateFormat.parse(expiredDate));
cal.add(Calendar.DATE, -1);
expiredDate = dateFormat.format(cal.getTimeInMillis());
} catch (ParseException e) {
e.printStackTrace();
}
Toast.makeText(LoanBook.this,
expiredDate, Toast.LENGTH_LONG)
.show();
This returns me the next date instead of previous date. Do you have any ideas?
Using Java's (pre-8) built-in Date and Time API will eat you alive. Use JodaTime for complex DateTime manipulations.
Getting the previous day is as simple as this.
DateTime dateTime = new DateTime();
System.out.println(dateTime);
System.out.println(dateTime.minusDays(1));
If you don't want any external libraries:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String strDate = "2014-10-28";
Date date = sdf.parse(strDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -1);
Date yesterday = calendar.getTime();
System.out.println(yesterday);
System.out.println(date);
Have you tried JodaTime? It is a fantastic library to do date manipulation easily. In fact, a lot of Java 8 date handling are derived from JodaTime.
For your needs, you could do something like:
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dt = formatter.parseDateTime(expiredDate);
DateTime dayBefore = dt.minusDays(1);
The other two answers are basically correct. But they omit the crucial issue of time zones and start of day. If you want all of yesterday, do something like the following.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime yesterdayStart = now.minusDays( 1 ).withTimeAtStartOfDay();
Convert to a java.sql.Timestamp.
java.sql.Timestamp ts = new java.sql.Timestamp( yesterdayStart.getMillis() );

Using Date instead of Timestamp

My code:
Calendar calendar = DateProvider.getCalendarInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
calendar.set(Calendar.YEAR, 1970);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.DATE, 1);
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
I want to eliminate the use of time stamp in this situation, how can achieve the same thing here with epochTimeStamp without using java.sql.Timestamp? I need the format to be same as if I was using Timestamp.
Since you need a String representation of your Date, then use SimpleDateFormat to convert the Date object into a String:
Calendar calendar = ...
//...
date = calendar.getTime();
Timestamp epochTimeStamp = new Timestamp(date.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
try {
System.out.println(sdf.format(date));
System.out.println(sdf.format(epochTimeStamp));
} catch (Exception e) {
//handle it!
}
From your example, prints
01/01/1970 09:21:18
01/01/1970 09:21:18
This gives you the epoch time in the same format as TimeStamp:
public class FormatDate {
public static void main(String[] args) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd kk:mm:ss:SSS");
LocalDateTime datetime = LocalDateTime.of(1970, 1, 1, 0, 0);
System.out.println(datetime.format(format));
}
}
Another way to represent date time objects in Java is to use the Joda Time libraries.
import org.joda.time.LocalDate;
...
LocalDate startDate= new LocalDate();//"2014-05-06T10:59:45.618-06:00");
//or DateTime startDate = new DateTime ();// creates instance of current time
String formatted =
startDate.toDateTimeAtCurrentTime().toString("MM/dd/yyy HH:mm:ss");
There are several ways to do formatting, setting and getting Time using these libraries that has been more reliable than using the JDK Date and Calendar libraries. These will persist in hibernate/JPA as well. If nothing else, this hopefully gives you options.

Calendar date to yyyy-MM-dd format in java

How to convert calendar date to yyyy-MM-dd format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.
A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date), Java uses Date.toString() to print the contents.
The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.time
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Joda-Time
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.
String myString=format1.format(date);
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
In order to parse a java.util.Date object you have to convert it to String first using your own format.
inActiveDate = format1.parse( format1.format(date) );
But I believe you are being redundant here.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));
This will display your date + 7 days in month, day and year format in a JOption window pane.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
My answer is for kotlin language.
You can use SimpleDateFormat to achieve the result:
val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)
for details click here.
OR
Use Calendar to do it for you:
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"
For more details check this answer.
I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).
Here is the one Liner:
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

Convert date to XMLGregorianCalendar

I have a date in the following format in UI..
Eg: Thu. 03/01
I convert them to XMLGregorianCalendar as below explained.
final DateFormat format = new SimpleDateFormat("E. M/d");
final String dateStr = closeDate;
final Date dDate = format.parse(dateStr);
GregorianCalendar gregory = new GregorianCalendar();
gregory.setTime(dDate);
XMLGregorianCalendar dealCloseDate = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(gregory);
My Output is "3/06/70 05:00 AM" instead of "3/06/2011 05:00 AM". What is the chnage required to get the proper year.
You didn't mention anything about how the year is supposed to be represented in this date conversion, but here is some pseudocode to get you started. Note that I don't explicitly deal with the timezone in this example:
final DateFormat format = new SimpleDateFormat("E. M/d");
final String dateStr = "Thu. 03/01";
final Date date = format.parse(dateStr);
GregorianCalendar gregory = new GregorianCalendar();
gregory.setTime(date);
XMLGregorianCalendar calendar = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(
gregory);
I did the following code to achieve the same. May be a lengthy code but is working fine.
def gregorianCalendar = new GregorianCalendar()
def xmlGregorianCalendar = newInstance().newXMLGregorianCalendar(gregorianCalendar)
if (//past date is needed) {
def date = xmlGregorianCalendar.toGregorianCalendar().time
def cal = Calendar.getInstance()
cal.setTime(date)
cal.add(Calendar.DATE,-3); //subtract 3 days
date.setTime(cal.getTime().getTime())
gregorianCalendar.setTime(date)
xmlGregorianCalendar = newInstance().newXMLGregorianCalendar(gregorianCalendar)
}

Categories

Resources