Convert calendar to string in java

Convert Date to ISO 8601 String in Java

Convert Java dates to ISO-8601 string: this post explains how to convert java.util.Date, java.util.Calendar, java.time.ZonedDateTime to string.

In Java, converting date objects to string is difficult, because the built-in APIs are similar and confusing. However, as a developer, we cannot avoid this topic — manipulating date objects is essential in our daily mission. Let’s see how to convert different dates to string correctly.

In the following paragraphs, I’ll use ISO 8601, an international standard covering the exchange of date and time-related data, as the string format. Date and time expressed according to ISO 8601 is:

2017-02-16T20:22:28+00:00 2017-02-16T20:22:28.000+00:00 

java.util.Date

Here’s an example to demonstrate how to convert a java.util.Date to ISO 8601 date string. This is a little bit tricky because we’re using the current time, which is the easiest use-case. For other cases, I believe using java.util.Calendar , java.util.GregorianCalendar would be a better solution. You can see the difference in the following paragraphs.

// Input Date date = new Date(System.currentTimeMillis()); // Conversion SimpleDateFormat sdf; sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); sdf.setTimeZone(TimeZone.getTimeZone("CET")); String text = sdf.format(date); // Output // "2017-02-16T21:00:00.000+01:00"

java.util.Calendar

When using Calendar , we need to get an instance, then build a date object with it. Please be aware that setting the field of millisecond is necessary: lack of such line will lead to an erroneous value for millisecond. A non-zero value will be filled.

// Input Calendar calendar = Calendar.getInstance(); calendar.set(2017, Calendar.FEBRUARY, 16, 20, 22, 28); calendar.set(Calendar.MILLISECOND, 0); Date date = calendar.getTime(); // Conversion SimpleDateFormat sdf; sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); sdf.setTimeZone(TimeZone.getTimeZone("CET")); String text = sdf.format(date); // Output // "2017-02-16T20:22:28.000+01:00"

java.util.GregorianCalendar

For gregorian calendar, we don’t need to set explicitly the millisecond datepart to 0, which is better than calendar. However, we still need to use java.util.Date as an intermediate to format the date.

// Input GregorianCalendar calendar; calendar = new GregorianCalendar(2017, Calendar.FEBRUARY, 16, 20, 22, 28); Date date = calendar.getTime(); // Conversion SimpleDateFormat sdf; sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); sdf.setTimeZone(TimeZone.getTimeZone("CET")); String text = sdf.format(date); // Output // "2017-02-16T20:22:28.000+01:00"

java.time.ZonedDateTime

The package java.time , formerly Joda-Time, provides the most elegant solution among all the possibiliites here. It uses a builder to construct the date time with time zone step-by-step. Then this object accepts a formatter to format the date representation in string. Its month is a base-1 number, which means that January is equal to 1 instead of 0, so you can use the digit instead of the static Java field. Let’s see the code:

// Input ZonedDateTime d = LocalDate .of(2017, 2, 16) .atTime(20, 22, 28) .atZone(ZoneId.of("CET")); // Conversion String text = DateTimeFormatter.ISO_DATE_TIME.format(d); // Output // "2017-02-16T20:22:28+01:00[CET]"

Use customized date-time pattern:

// Conversion DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX").format(d); // Output // "2017-02-16T20:22:28.000+01:00"

Patterns for formatting and parsing are available in the Javadoc of DateTimeFormatter (Java 8).

Conclusion

In this blog, we have seen different methods to create a date object and the associated way to cast that object into an ISO 8601 date representation. I demonstrated that common date object types can be used to convert into string, but most of them are hard to understand, and time-zone is not well supported. However, thanks to the implementation of JSR 310, Joda-Time is now migrated into Java SE 8 as package java.time .

By the way, if you need to use any of the code shown in this blog, feel free to use them and adapt into your own code. Happy coding and have a nive weekend!

This work is licensed under a Attribution 4.0 International license.

Источник

Java Convert Calendar to String

In this Java core tutorial we learn how to convert a java.util.Calendar object to a date time format String in Java programming language.

How to format Calendar to date time String

In Java we can use SimpleDateFormat class to format a Date object into date time String. The following Java program we use the SimpleDateFormat to format Date object which return from Calendar.getTime() method of a given Calendar object.

import java.text.SimpleDateFormat; import java.util.Calendar; public class ConvertCalendarToStringExample1  public static void main(String. args)  Calendar calendar = Calendar.getInstance(); // Convert Calendar to String SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String formattedDate = simpleDateFormat.format(calendar.getTime()); System.out.println(formattedDate); > >

Источник

Convert calendar to string in java

Let’s see the full example to convert date and time into String in java using format() method of java.text.SimpleDateFormat class.

Date Format with MM/dd/yyyy : 04/13/2015 Date Format with dd-M-yyyy hh:mm:ss : 13-4-2015 10:59:26 Date Format with dd MMMM yyyy : 13 April 2015 Date Format with dd MMMM yyyy zzzz : 13 April 2015 India Standard Time Date Format with E, dd MMM yyyy HH:mm:ss z : Mon, 13 Apr 2015 22:59:26 IST

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Convert Date to String in Java

Convert Date to String in Java

  1. Convert Date to String Using SimpleDateFormat in Java
  2. Convert Date to String Using DateFormatUtils Class in Java
  3. Convert Date to String Using DateTimeFormatter in Java
  4. Convert Date to String With the Time Zone in Java
  5. Convert Date to String With String Class in Java

This tutorial introduces how to convert java.util.Date to String in Java and lists some example codes to understand it.

Java has several classes and methods that help convert Date to String like using SimpleDateFormat , DateFormatUtils , and DateTimeFormatter class.

Convert Date to String Using SimpleDateFormat in Java

Here, We use format() method of SimpleDateFormat class to get String from the util.Date object in Java.

import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;  public class SimpleTesting    public static void main(String[] args) throws ParseException   DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");  Date date = new Date();  String dateToStr = dateFormat.format(date);  System.out.println("Date is "+ dateToStr);  > > 

Convert Date to String Using DateFormatUtils Class in Java

If you are using the Apache library then use format() method of DateFormateUtils class. It returns a string after converting java.util.Date to string in Java.

import java.text.ParseException; import java.util.Date; import org.apache.commons.lang3.time.DateFormatUtils;  public class SimpleTesting    public static void main(String[] args) throws ParseException   Date date = new Date();  String dateToStr = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:SS");  System.out.println("Date is "+ dateToStr);  > > 

Convert Date to String Using DateTimeFormatter in Java

Here, we use the format() method that takes the ofPattern() method as an argument and returns a string representation of a date. See the example below.

import java.text.ParseException; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date;  public class SimpleTesting    public static void main(String[] args) throws ParseException   Date date = new Date();  String dateToStr = date.toInstant()  .atOffset(ZoneOffset.UTC)  .format( DateTimeFormatter.ofPattern("dd-MM-yyyy"));  System.out.println("Date is "+ dateToStr);  > > 

Convert Date to String With the Time Zone in Java

Here, we use format() method of the DateTimeFormatter class to get string after conversion from java.util.date . We get time zone along with date because we specified the date-time format in the ofPattern() method.

import java.text.ParseException; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date;  public class SimpleTesting    public static void main(String[] args) throws ParseException   Date date = new Date();  DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")  .withZone(ZoneId.systemDefault());  String dateToStr = format.format(date.toInstant());  System.out.println("Date is "+ dateToStr);  > > 
Date is 2020-09-21 09:10:23:991 +0530 

Convert Date to String With String Class in Java

This is one of the simplest solutions to get a String of java.util.date object. Here, we use the format() method of the String class that formats the date based on the specified format. See the example below.

import java.text.ParseException; import java.util.Date;  public class SimpleTesting    public static void main(String[] args) throws ParseException   Date date = new Date();  String dateToStr = String.format("%1$tY-%1$tm-%1$td", date);  System.out.println("Date is "+ dateToStr);  > > 

Related Article — Java String

Related Article — Java DateTime

Источник

Читайте также:  Next или nextline java
Оцените статью