Welcome!

Java IoT Authors: Elizabeth White, Paul Simmons, Liz McMillan, Yeshim Deniz, Pat Romanski

Related Topics: Java IoT

Java IoT: Blog Feed Post

Java 8: Date and Time | Part I

Since time is a natural concept, in an ideal world, dealing with it should be simple

Wikipedia defines Time as:

"Time is a measure in which events can be ordered from the past through the present into the future, and also the measure of durations of events and the intervals between them.Time is often referred to as the fourth dimension, along with the three spatial dimensions."

Since Time is a natural concept, in an ideal world, dealing with it should be simple, but unfortunately it is not the case and we humans made it more complex by introducing different time zones and day light saving.

As a programmer, we want that programming languages immune us from these complexity and being a Java programmer, we have similar expectations from Java. Java tried to overcome these complexities in its first two editions of Date and Time API, but failed measurably. A simple google will give you numerous posts criticizing Java for this. Few years back, I was introduced to Joda-Time library that provide APIs that help you to work with Time with ease.

In its latest edition (Java 8), in its third attempt, finally Java brought this change that we all were looking for long. With its new APIs, it is no more require to use either third party APIs or create several utility classes/methods to deal with date and time.  This new API is heavily inspired by Joda-Time library.

Java 8 - Date and Time API
New API defines classes to map the concepts of Instant, Duration, Period, Time (Local and Zoned). All the classes are immutable and thread safe. Official java.time package summary offers a great detail on the different concepts and worth a visit.

Instant and Duration:
In Java, an Instant represents a point on the time line. An origin, called the epoch, is arbitrarily set at midnight of January 1, 1970 GMT. This is the same convention used in the Unix/POSIX time. Starting from that origin, time is measured in 86,400 seconds per day, forwards and backwards, in nanosecond precision. Instant is essentially a timestamp.
Duration is amount of time between two instants. Both instants and duration are scalar values, that mean time zone or day light saving doesn't affect them.

Getting Current Instant:

Instant instant = Instant.now();

Duration between two instants:

Instant startInstant = Instant.now();
Instant endInstant = Instant.now();
Duration duration = Duration.between(startInstant,endInstant);

Adding time to a duration is pretty straight forward:

public void editDuration(Duration duration){
// Enhance Duration by 5 minutes
Duration enhanceDurationByMinute = duration.plusMinutes(5);

//Enhance Duration by 2 Days, 5 hours, 6 minutes,
// 10 Seconds, 200 milliseconds and 788 nanoseconds
Duration enchanced = duration.plusDays(2).plusHours(5).plusMinutes(6)
.plusSeconds(10).plusMillis(200).plusNanos(788);

}

Important point to note here is, since Duration is an immutable, every time you call a plusXXX() method, it returns a new object of Duration.

Duration stores time in two parts, seconds and nano seconds and provide two methods to get these parts. It provides methods to get total time in different units viz. milliseconds, minutes, hours.

Getting Duration in human readable form:

public static void getDurationBetweenTwoInstants(){
Logger logger = Logger.getGlobal();
Instant startInstant = Instant.now();
for(int i = 0; i < Integer.MAX_VALUE; i++){
//Do nothing
}
Instant endInstant = Instant.now();
Duration duration = Duration.between(startInstant, endInstant);
logger.log(INFO, "" + duration);
duration = duration.plusHours(5).plusMinutes(8).plusSeconds(2)
.plusMillis(234).plusNanos(234);
logger.log(INFO, "Total Time :" + duration);

logger.log(INFO, "NanoSecond Part of Total Time: "
+ duration.getNano());
logger.log(INFO,"Seconds Part of Total Time: "
+ duration.getSeconds());

logger.log(INFO,"Total time in Nano : " + duration.toNanos());
logger.log(INFO,"Total time in Millis : " + duration.toMillis());
logger.log(INFO,"Total time in Minutes : " + duration.toMinutes());
logger.log(INFO,"Total time in Hours : " + duration.toHours());
}

A sample Output of above program looks like:

INFO: Time in looping: PT0.006S
INFO: Total Time :PT5H8M2.240000234S
INFO: NanoSecond Part of Total Time: 240000234
INFO: Seconds Part of Total Time: 18482
INFO: Total time in Nano : 18482240000234
INFO: Total time in Millis : 18482240
INFO: Total time in Minutes : 308
INFO: Total time in Hours : 5

Similar methods exists for subtraction as well.

Conclusion
Instants and Duration is the basis of new Date and Time API. But as you can see, both the APIs are not that useful from human being interaction and for that there are other APIs that relates to Periods, Local and Zoned Date/Time. I will discuss about them in my next post.

Read the original blog entry...

More Stories By Vineet Mangal

Vineet Mangal is a Java Developer with close to 7 years of experience. He has worked in different Java domains such as Core Java, Multithreading, JEE stack and frameworks such as JUnit, TestNG, JMockit, Hibernate. He loves to design new generic frameworks that can be plugged in anywhere (though mostly he designs them for his projects only, but they are scalable).

@ThingsExpo Stories
Michael Maximilien, better known as max or Dr. Max, is a computer scientist with IBM. At IBM Research Triangle Park, he was a principal engineer for the worldwide industry point-of-sale standard: JavaPOS. At IBM Research, some highlights include pioneering research on semantic Web services, mashups, and cloud computing, and platform-as-a-service. He joined the IBM Cloud Labs in 2014 and works closely with Pivotal Inc., to help make the Cloud Found the best PaaS.
Headquartered in Plainsboro, NJ, Synametrics Technologies has provided IT professionals and computer systems developers since 1997. Based on the success of their initial product offerings (WinSQL and DeltaCopy), the company continues to create and hone innovative products that help its customers get more from their computer applications, databases and infrastructure. To date, over one million users around the world have chosen Synametrics solutions to help power their accelerated business or per...
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Founded in 2000, Chetu Inc. is a global provider of customized software development solutions and IT staff augmentation services for software technology providers. By providing clients with unparalleled niche technology expertise and industry experience, Chetu has become the premiere long-term, back-end software development partner for start-ups, SMBs, and Fortune 500 companies. Chetu is headquartered in Plantation, Florida, with thirteen offices throughout the U.S. and abroad.
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, led attendees through the exciting evolution of the cloud. He looked at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering m...
From 2013, NTT Communications has been providing cPaaS service, SkyWay. Its customer’s expectations for leveraging WebRTC technology are not only typical real-time communication use cases such as Web conference, remote education, but also IoT use cases such as remote camera monitoring, smart-glass, and robotic. Because of this, NTT Communications has numerous IoT business use-cases that its customers are developing on top of PaaS. WebRTC will lead IoT businesses to be more innovative and address...
Rodrigo Coutinho is part of OutSystems' founders' team and currently the Head of Product Design. He provides a cross-functional role where he supports Product Management in defining the positioning and direction of the Agile Platform, while at the same time promoting model-based development and new techniques to deliver applications in the cloud.
Business professionals no longer wonder if they'll migrate to the cloud; it's now a matter of when. The cloud environment has proved to be a major force in transitioning to an agile business model that enables quick decisions and fast implementation that solidify customer relationships. And when the cloud is combined with the power of cognitive computing, it drives innovation and transformation that achieves astounding competitive advantage.
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
In his session at Cloud Expo, Alan Winters, U.S. Head of Business Development at MobiDev, presented a success story of an entrepreneur who has both suffered through and benefited from offshore development across multiple businesses: The smart choice, or how to select the right offshore development partner Warning signs, or how to minimize chances of making the wrong choice Collaboration, or how to establish the most effective work processes Budget control, or how to maximize project result...
Personalization has long been the holy grail of marketing. Simply stated, communicate the most relevant offer to the right person and you will increase sales. To achieve this, you must understand the individual. Consequently, digital marketers developed many ways to gather and leverage customer information to deliver targeted experiences. In his session at @ThingsExpo, Lou Casal, Founder and Principal Consultant at Practicala, discussed how the Internet of Things (IoT) has accelerated our abilit...
In his keynote at 19th Cloud Expo, Sheng Liang, co-founder and CEO of Rancher Labs, discussed the technological advances and new business opportunities created by the rapid adoption of containers. With the success of Amazon Web Services (AWS) and various open source technologies used to build private clouds, cloud computing has become an essential component of IT strategy. However, users continue to face challenges in implementing clouds, as older technologies evolve and newer ones like Docker c...
Data is the fuel that drives the machine learning algorithmic engines and ultimately provides the business value. In his session at Cloud Expo, Ed Featherston, a director and senior enterprise architect at Collaborative Consulting, discussed the key considerations around quality, volume, timeliness, and pedigree that must be dealt with in order to properly fuel that engine.
No hype cycles or predictions of zillions of things here. IoT is big. You get it. You know your business and have great ideas for a business transformation strategy. What comes next? Time to make it happen. In his session at @ThingsExpo, Jay Mason, Associate Partner at M&S Consulting, presented a step-by-step plan to develop your technology implementation strategy. He discussed the evaluation of communication standards and IoT messaging protocols, data analytics considerations, edge-to-cloud tec...
In his keynote at 18th Cloud Expo, Andrew Keys, Co-Founder of ConsenSys Enterprise, provided an overview of the evolution of the Internet and the Database and the future of their combination – the Blockchain. Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settl...
In his session at @ThingsExpo, Dr. Robert Cohen, an economist and senior fellow at the Economic Strategy Institute, presented the findings of a series of six detailed case studies of how large corporations are implementing IoT. The session explored how IoT has improved their economic performance, had major impacts on business models and resulted in impressive ROIs. The companies covered span manufacturing and services firms. He also explored servicification, how manufacturing firms shift from se...
IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...
Organizations planning enterprise data center consolidation and modernization projects are faced with a challenging, costly reality. Requirements to deploy modern, cloud-native applications simultaneously with traditional client/server applications are almost impossible to achieve with hardware-centric enterprise infrastructure. Compute and network infrastructure are fast moving down a software-defined path, but storage has been a laggard. Until now.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...