How to convert ZonedDateTime to XMLGregorianCalendar in Java 7 - java-8

My java 7 application consuming a service whcih is in Java 8 , i am receiving a date as string like
"2020-04-13T12:36:13Z"
which is actually a ZonedDateTime.
i need to convert this string to XMLGregorianCalendar and send to another service ?
Since my application is in java 7 i could not parse the string to ZonedDateTime . Is there any way i can do this conversion ?

Easy when you know how.
String receivedDateTimeString = "2020-04-13T12:36:13Z";
XMLGregorianCalendar xmlgc = DatatypeFactory.newInstance()
.newXMLGregorianCalendar(receivedDateTimeString);
System.out.println(xmlgc);
Output:
2020-04-13T12:36:13Z
ZonedDateTime.toString() sometimes produces ISO 8601 format (and sometimes an extended format with a zone ID that is not part of ISO 8601). In your case you have got pure ISO 8601. Dates and times in XML documents use a variant of ISO 8601, it’s close enough that we can consider them the same for our purpose here. So an XMLGregorianCalendar instance is created directly from the ISO 8601 string, and its toString method produces the same ISO 8601 string back.
ThreeTen Backport allows you to use ZonedDateTime in Java 7
You can, and you may prefer to use ZonedDateTime in Java 7 too rather than XMLGregorianCalendar. This use goes through ThreeTen Backport, the backport of java.time to Java 6 and 7, see the links at the bottom.
import org.threeten.bp.ZonedDateTime;
public class DemoZonedDateTimeInJava7 {
public static void main(String[] args) {
String receivedDateTimeString = "2020-04-13T12:36:13Z";
ZonedDateTime zdt = ZonedDateTime.parse(receivedDateTimeString);
System.out.println(zdt);
}
}
2020-04-13T12:36:13Z
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601

Related

Getting JDBC & Saxon DateTime data as a ZonedDateTime object

We have a bunch of code that gets a DateTime from JDBC, Saxon (XPath), dom4j, jway json-path (JPath), & OData as a Date object. We're now up on Java 1.8 and my first question is do I want to now try to get any data that I used to get as a Date object to now get it as a ZonedDateTime object? Or should I be using something else?
My second question is how do I read the data from JDBC, Saxon, etc as ZonedDateTime objects?
tl;dr
Never use the legacy classes, use only java.time.
When you must, convert using new methods added to the old classes.
As of JDBC 4.2, exchange java.time objects with your database, never strings or java.sql types.
Do most of your work in UTC. Adjust into a time zone only for presentation.
When communicating date-time values as text, use ISO 8601 formats.
Search Stack Overflow for more info.
Avoid legacy date-time classes
The terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, java.text.SimpleDateFormat, java.sql.Timestamp, and java.sql.Date are all entirely supplanted by the java.time classes. No need to ever touch those awful old classes again.
The java.time classes have been bundled with Java 8 and later for a few years now. They have proven themselves to be a reliable, industry-leading framework for date-time work. They were inspired by the lessons learned from the excellent Joda-Time project (now in maintenance-mode). So the java.time classes have “an old soul”, and are not some limited “1.0” rough draft.
Conversion
For interoperating with old code not yet updated to the java.time classes, you can easily convert back-and-forth between the legacy classes and modern classes. For conversions, look to new methods added to the old classes. Read Questions such as this to learn more.
Database
As of JDBC 4.2 and later, you can directly exchange java.time objects with your database. No need to ever use the badly-designed java.sql classes again for date-time values.
Generally best to use Instant for values in a column of type akin to the SQL-standard TIMESTAMP WITH TIME ZONE.
myPreparedStatement.setObject( … , instant ) ;
And retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
ISO 8601
When exchanging date-time values outside of a JVM, serialize to text using the standard ISO 8601 formats. These formats are designed to be useful and practical, easy to parse by machines, easy to read by humans across cultures.
The java.time classes use the ISO 8601 formats by default when parsing/generating strings. The ZonedDateTime class extends the standard by wisely appending the name of the zone in square brackets.
Zones
data that I used to get as a Date object to now get it as a ZonedDateTime object?
The java.util.Date class is directly replaced by Instant. Both represent a moment in UTC. The modern class resolves to nanoseconds instead of milliseconds.
Instant instant = myJavaUtilDate.toInstant() ; // Convert from legacy class to modern.
In databases such as Postgres, a column of type TIMESTAMP WITH TIME ZONE actually does not have its time zone saved. Instead, any offset or zone passed with an incoming value is used by the database to adjust into UTC. The resulting UTC moment is saved to the database, and the original zone/offset is discarded. If you need the original zone/offset, you must manually save it to an extra column yourself.
So, generally best to pass and fetch Instant objects with your database for a moment on the timeline.
To learn about the concept of a date-time not on the timeline, search for LocalDateTime class, and read postings like this Question, What's the difference between Instant and LocalDateTime?.
Be aware that the SQL standard barely touches on the tricky topic of date-time handling. It defines a few types but says little about behavior. So databases vary widely in their implementations. Be sure to study and experiment to verify your understanding of your database and driver.
read the data from JDBC, Saxon, etc as ZonedDateTime objects?
Generally the best practice is to work in UTC. That means the Instant class rather than ZonedDateTime class.
If receiving a Date, convert to Instant as shown above.
Usually you want to do your business logic, storage, exchange, logging, and tracing/debugging all in UTC. Apply a time zone only where required by business requirements or for presentation to a user.
With a Instant in hand, you can adjust to the wall-clock time used by the people of a particular region by assigning a time zone. Apply a ZoneId to get a ZonedDateTime.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Search Stack Overflow
Your Question is really a duplicate of many others such as this. I suggest you search Stack Overflow for the various java.time class names. You will learn much as there have been plenty of questions and answers already posted.
Compatible libraries
Many Java libraries have been updated to work with java.time types.
Check for the latest versions of libraries you may be using, and read their documentation to learn about added support.
If not directly supported, libraries that accept converters/formatters/plugins will likely have some java.time ones already written. Search for them, or ask on the sister site: Software Recommendations Stack Exchange.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to implement Java 8 Stream API using Java 7 or older?

I was asked this question in a job interview (Microsoft).
methods to implement for example:
.stream(), .filter(), .map() , flatMap() , min() , count() , reduce() , groupBy()
etc
It's quite an open question but I think is an interesting one.
Thanks
One way to get an ability to use StreamAPI in your Java7 and Java6 projects add a streamsupport library https://github.com/streamsupport/streamsupport Streamsupport is a backport of the Java 8 java.util.function (functional interfaces) and java.util.stream (streams) API for users of Java 6 or 7
Here is a good example: Lightweight-Stream-API. It implements almost all stream APIs for Android/Java 7 by iterators.
I would not waste time creating those functions myself as it also implies quite rigorous testing. I would rather use Kotlin. It works with any Java starting from 6 and has all of these features (including lambdas) plus many others. Additionally it provides quite good compatibility with the core Java partially solving deficiencies of generics implementation.

Comparison between jdk1.6 and jdk1.8 code with Example

I would like to understand how jdk1.8 code is, as compared to code of jdk1.6
Can anyone provide an example, or a link??
Thanks
I want to see a comparison between code written in java6 and cod written in java8,
to understand the features of java8 and how it simplifies the code
I just need an example of a program written in java6 , against a program written in java8
The below link will help you understand how Java8 feature 'Lambda Expression' simplifies the code.
Java8 Lambda Expression - The What and Why
There are many features available in Java 8 and code enhancement that was not available in java 6.
A useful compiler feature that is added in Java 7 is the 'diamond operator'. E.g, instead of typing
ArrayList<Integer> arrInt = new ArrayList<Integer>();
You could just type
ArrayList<Integer> arrInt = new ArrayList<>();
In Java 8 many features are available. For further details you may visit mentioned links
https://www.javacodegeeks.com/2014/03/8-new-features-for-java-8.html
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html

Swift 2.2: #if swift(>=x.y) version build configuration: can it be used to check sub-versions? (E.g. distinguish Swift 2.1 from 2.1.1)

With Swift 2.2, we can now make use of the #if swift(>=x.y) version build configuration, as proposed in SE-0020 of Swift evolution.
#if swift(>=2.2)
print("Active!")
#else
this! code! will! not! parse! or! produce! diagnostics!
#endif
I've tried, out of curiosity, to attempt to use this with one step lower subversion level comparison (say >=2.1.1 without passing Swift 2.1 from XCode 7.1 beta 2), but my own attempts don't really work:
>=x.y.z yields an error,
expected named member of numeric literal
>=x.y with y = 11 naturally compiles and passes but as a version we're yet to see, 2.11.
I can't find any further details regarding this in the XCode 7.3 release notes.
Question: Is this new version build configuration limited to a single .y subversion, or is there some trick to circumvent this?
Answer: The new version build configuration is limited to two version components.
From Swift Evolution, proposal SE-0020: Swift Language Version Build Configuration
Detailed design
...
For now, we'll only expect up to two version components, since it will
be unlikely that a syntax change will make it in a +0.0.1 revision.
More details can be found in the associated Swift Evolution thread, most specifically in this exchange between Chris Lattner and Douglas Gregor:
On Dec 18, 2015, at 3:34 PM, Douglas Gregor via swift-evolution wrote:
...
On Dec 18, 2015, at 12:29 PM, Chris Lattner via swift-evolution wrote:
...
The argument to use a string is if we wanted to support subversions, e.g. like “#if swift(2.2.1)”. This requires the parameter to be a string, because 2.2.1 isn’t a valid floating point literal - the lexer will be displeased.
...
This feature LGTM, and I also prefer that we drop the quotes.
Two levels of version number should be sufficient.

Portable Class Library HttpUtility.UrlEncode

I understand that making web requests is quite well supported in the Portable Class Library. Is there any equivelant of HttpUtility.UrlEncode in the PCL? I need it for Windows Phone and Metro applications.
Use Uri.EscapeUriString and Uri.EscapeDataString
The only difference between the two is that EscapeDataString also encodes the RFC 2396 reserved characters which includes these characters ;/?:#&=+$,
It is important to note that neither of these methods encodes the RFC 2396 unreserved characters which includes -_.!~*'()
So if you need these encoded then you will have to manually encode them.
WebUtility
In portable class libraries lucky enough to be targeting .NET 4.5 (e.g. Profile7), many of the HttpUtility methods have siblings in System.Net.WebUtility.
using System.Net;
WebUtility.UrlEncode("some?string#");
Potential Warning
While some of the sibling methods appear to be identical to their HttpUtility counterparts, this one has a slight difference between the resulting encodings. WebUtility.UrlEncode generates uppercase encodings while HttpUtility.UrlEncode generates lowercase encodings.
WebUtility.UrlEncode("?") // -> "%3F"
HttpUtility.UrlEncode("?") // -> "%3f"
Make It Backwards Compatible
If you are dependent on your PCL code generating exactly what you would have generated with prior HttpUtility code, you could create your own helper method around this method and regex it.
using System.Text.RegularExpressions;
public static string UrlEncodeOldSchool(string value) {
var encodedValue = WebUtility.UrlEncode(value);
return Regex.Replace(encodedValue, "(%[0-9A-F]{2})",
encodedChar => encodedChar.Value.ToLowerInvariant());
}
(Even though this is a simple one, always regex at your own risk.)

Resources