ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

How to convert one date format to another date format in Java?

Updated on January 8, 2014

If you are a Java programmer or Java Developer, then you sometimes need to convert date from one format to anther format. For example, you are working a web based Java application. The application supports order processing with date. When a order is successfully created, you need to save the order details with date. The application has String date but you have to save that date into Date format into your application database. Or sometimes your application accepts yyMMdd format data but you have to store ddMMYYYY format data into your application database. For this type of situation, you have to struggle with date formatting. Date formatting or converting one date format to another date format can be done easily using SimpleDateFormat. In this page, we will see some examples of changing the format of date form one format to another. For simplicity and easy understanding, we divide the whole thing into four parts. All the parts are:

Part A: How to format a Date object from one format to another format using SimpleDateFormat

  • Example 1: Formatting from a default Date object to yyMMdd format
  • Example 2: Formatting from a default Date object to yyyyMMdd format
  • Example 3: Formatting from a default Date object to yyyy-MM-dd HH:mm:ss format

Part B: How to convert a date string from date string to default Date object
Part C: How to convert a date string from date string to another format using SimpleDateFormat

  • Example 1: Convert string format date ("MM/dd/yyyy") into "yyMMdd" format date
  • Example 2: Convert string format date ("MM/dd/yyyy") into "MM-dd-yyyy hh:mm:ss" format date

Part D: Some exercises

  • Exercise 1: Formatting Minutes using SimpleDateFormat
  • Exercise 2: Formatting day using SimpleDateFormat
  • Exercise 3: Formatting year using SimpleDateFormat
  • Exercise 4: Formatting TimeZone using SimpleDateFormat

In the following sections, you will find each part in details with complete one or more examples.

Step 1:

Create a Date object. For example, we want to create a Date object which holds the value of today's date. We can do so by writing the following line of Java code:

Date today = new Date();

Step 2:

Think about the desired date format. Date format can be several types like MMddyy, yyMMdd, dd/MM/yy etc. For example, we want the date format of yyMMdd.

Step 3:

Create a SimpleDateFormat object and pass the desired date format. We can do this by using he following line Java code:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");

Step 4:

Use format method of SimpleDateFormat class to format the date. We can do this by the following line of Java code:

 simpleDateFormat.format(today);

Java source code

package com.hubpages.plusminus;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		Date today = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
		String myDateString = simpleDateFormat.format(today);

		System.out.println("Example of SimpleDateFormat");
		System.out
				.println("=================================================================");
		System.out.println("Before formatting [default format]: " + today);
		System.out.println("After formatting  [yyMMdd format ]: " + myDateString);

	}

}

Sample output

Example 2: Formatting from a default Date object to yyyyMMdd format

package com.hubpages.plusminus;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		Date today = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String myDateString = simpleDateFormat.format(today);

		System.out.println("Example of SimpleDateFormat");
		System.out
				.println("=================================================================");
		System.out.println("Before formatting [default format ]: " + today);
		System.out.println("After formatting  [yyyyMMdd format]: " + myDateString);

	}

}

Output of example 2

Example 3: Formatting from a default Date object to yyyy-MM-dd HH:mm:ss format

package com.hubpages.plusminus;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		Date today = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String myDateString = simpleDateFormat.format(today);

		System.out.println("Example of SimpleDateFormat");
		System.out
				.println("============================================================================");
		System.out.println("Before formatting [default format            ]: " + today);
		System.out.println("After formatting  [yyyy-MM-dd HH:mm:ss format]: " + myDateString);

	}

}

Sample output

Example 3: Formatting from a default Date object to MM/dd/yyyy format

package com.hubpages.plusminus;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		Date today = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
		String myDateString = simpleDateFormat.format(today);

		System.out.println("Example of SimpleDateFormat");
		System.out
				.println("===================================================================");
		System.out.println("Before formatting [default format   ]: " + today);
		System.out.println("After formatting  [MM/dd/yyyy format]: " + myDateString);

	}

}

Sample output

Step 1:

Declare a String variable and initialize it with the date string containing date in one format. For example, we want to convert the string 01/01/2014. Using Java we initialize the string into a String variable like the following:

String dateString = "01/01/2014";

Step 2:

Look carefully the format of the String. We must have to define the format into the SimpleDateFormat object during the object creation. For our example, the format is like MM/dd/yyyy.

Step 3:

Now, create SimpleDateFormat object with source string date format. The Java code for this will be like the following:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");

Step 4:

Using the parse method of SimpleDateFormat class, format the date string into Date object. Java code for this will be the following:

simpleDateFormat.parse(dateString);

Full code

package com.hubpages.plusminus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		String dateString = "01/01/2014";
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
		try {
			Date date = simpleDateFormat.parse(dateString);
			System.out.println("Example of SimpleDateFormat");
			System.out.println("===================================================================");
			System.out.println("Before formatting [default format   ]: "+ dateString);
			System.out.println("After formatting  [MM/dd/yyyy format]: " + date);
		} catch (ParseException e) {
			e.printStackTrace();
		}


	}

}

Sample output

Step 1:

Declare a String variable and initialize it with the date string containing date in one format. For example, we want to convert the string 01/01/2014. Using Java we initialize the string into a String variable like the following:

String originalDateString = "01/01/2014";

Step 2:

Look carefully the format of the String. We must have to define the format into the SimpleDateFormat object during the object creation. For our example, the format is like MM/dd/yyyy.

Step 3:

Now, create SimpleDateFormat object with source string date format. The Java code for this will be like the following:

SimpleDateFormat sourseFormat = new SimpleDateFormat("MM/dd/yyyy");

Step 4:

Using the parse method of SimpleDateFormat class, format the date string into Date object. Java code for this will be the following:

Date date = sourseFormat.parse(originalDateString);

Step 5:

Think about the desired date format. Date format can be several types like MMddyy, yyMMdd, dd/MM/yy etc. For example, we want the date format like yyMMdd. So, the Java code for this will be like the following:

SimpleDateFormat destinationForamt = new SimpleDateFormat("yyMMdd");

Step 6:

Use format method of SimpleDateFormat class to format the date. We can do this by the following line of Java code:

String finalDateForamt = destinationForamt.format(date);

Example 1: Convert string format date ("MM/dd/yyyy") into "yyMMdd" format date

package com.hubpages.plusminus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		String originalDateString = "01/01/2014";
		SimpleDateFormat sourseFormat = new SimpleDateFormat("MM/dd/yyyy");

		try {
			Date date = sourseFormat.parse(originalDateString);

			SimpleDateFormat destinationForamt = new SimpleDateFormat("yyMMdd");
			String finalDateForamt = destinationForamt.format(date);
			System.out.println("Formatting one date format to another date format");
			System.out.println("=================================================");
			System.out.println("Before formatting [String format]: "	+ originalDateString);
			System.out.println("After formatting  [yyMMdd format]: "	+ finalDateForamt);

		} catch (ParseException e) {
			e.printStackTrace();
		}

	}

}

Sample output

Example 2: Convert string format date ("MM/dd/yyyy") into "MM-dd-yyyy hh:mm:ss" format date

package com.hubpages.plusminus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		String originalDateString = "01/01/2014";
		SimpleDateFormat sourseFormat = new SimpleDateFormat("MM/dd/yyyy");

		try {
			Date date = sourseFormat.parse(originalDateString);

			SimpleDateFormat destinationForamt = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
			String finalDateForamt = destinationForamt.format(date);
			System.out.println("Formatting one date format to another date format");
			System.out.println("=====================================================================");
			System.out.println("Before formatting [String format             ]: "	+ originalDateString);
			System.out.println("After formatting  [MM-dd-yyyy hh:mm:ss format]: "	+ finalDateForamt);

		} catch (ParseException e) {
			e.printStackTrace();
		}

	}

}

Sample output

Exercise 1: Formatting Minutes using SimpleDateFormat

Write a Java program which could format the minutes like ss format in this way. For example if it is 1 second it will show 01 and if it is 12 second then it will show 12 i.e. it always shows 2 digit format of the date's time.

package com.hubpages.plusminus;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		Date today = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("ss");
		String myDateString = simpleDateFormat.format(today);

		System.out.println("Example of SimpleDateFormat");
		System.out
				.println("=================================================================");
		System.out.println("Before formatting [default format]: " + today);
		System.out.println("After formatting  [yyMMdd format ]: " + myDateString);

	}

}

Sample output

Exercise 2: Formatting day using SimpleDateFormat

Write a Java program which could format the day like dd format. For example if date is 8, it will show 08 and if it is 12, it will show 12 i.e. it always shows 2 digit format of the date's day.

package com.hubpages.plusminus;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		Date today = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd");
		String myDateString = simpleDateFormat.format(today);

		System.out.println("Example of SimpleDateFormat");
		System.out.println("=================================================================");
		System.out.println("Before formatting [default format]: " + today);
		System.out.println("After formatting  [yyMMdd format ]: " + myDateString);

	}

}

Sample output

Exercise 3: Formatting year using SimpleDateFormat

Write a Java program which could format the year like yyyy format. For example, the year will look like 2014.

Java source code

package com.hubpages.plusminus;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		Date today = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
		String myDateString = simpleDateFormat.format(today);

		System.out.println("Example of SimpleDateFormat");
		System.out.println("=================================================================");
		System.out.println("Before formatting [default format]: " + today);
		System.out.println("After formatting  [yyMMdd format ]: " + myDateString);

	}

}

Sample output

Exercise 4: Formatting TimeZone using SimpleDateFormat

Write a Java program which could format the year like "Eastern Standard Time"

Java source code

package com.hubpages.plusminus;

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatingDateUsingSimpleDateFormat {

	public static void main(String[] args) {

		Date today = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("zzzz");
		String myDateString = simpleDateFormat.format(today);

		System.out.println("Example of SimpleDateFormat");
		System.out.println("=================================================================");
		System.out.println("Before formatting [default format]: " + today);
		System.out.println("After formatting  [yyMMdd format ]: " + myDateString);

	}

}

Sample output

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Nikhil 4 years ago

      Thanks a ton

    • profile image

      Nina 4 years ago

      Awesome! What i was searching, I got more than that. This java codes are really helpful. Thank you.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)