Nitin Agrawal
Contact -
  • Home
  • Interviews
    • Secret Receipe
    • InterviewFacts
    • Resume Thoughts
    • Daily Coding Problems
    • BigShyft
    • Companies
    • Interviews Theory
  • Programming Languages
    • Java Script >
      • Tutorials
      • Code Snippets
    • Reactive Programming >
      • Code Snippets
    • R
    • DataStructures >
      • LeetCode Problems >
        • Problem10
        • Problem300
      • AnagramsSet
    • Core Java >
      • Codility
      • Program Arguments OR VM arguments & Environment variables
      • Java Releases >
        • Java8 >
          • Performance
          • NasHorn
          • WordCount
          • Thoughts
        • Java9 >
          • ServiceLoaders
          • Lambdas
          • List Of Objects
          • Code Snippets
        • Java14 >
          • Teeing
          • Pattern
          • Semaphores
        • Java17 >
          • Switches
          • FunctionalStreams
          • Predicate
          • Consumer_Supplier
          • Collectors in Java
        • Java21 >
          • Un-named Class
          • Virtual Threads
          • Structured Concurrency
      • Threading >
        • ThreadsOrder
        • ProducerConsumer
        • Finalizer
        • RaceCondition
        • Executors
        • Future Or CompletableFuture
      • Important Points
      • Immutability
      • Dictionary
      • Sample Code Part 1 >
        • PatternLength
        • Serialization >
          • Kryo2
          • JAXB/XSD
          • XStream
        • MongoDB
        • Strings >
          • Reverse the String
          • Reverse the String in n/2 complexity
          • StringEditor
          • Reversing String
          • String Puzzle
          • Knuth Morris Pratt
          • Unique characters
          • Top N most occurring characters
          • Longest Common Subsequence
          • Longest Common Substring
        • New methods in Collections
        • MethodReferences
        • Complex Objects Comparator >
          • Performance
        • NIO >
          • NIO 2nd Sample
        • Date Converter
        • Minimum cost path
        • Find File
      • URL Validator
    • Julia
    • Python >
      • Decorators
      • String Formatting
      • Generators_Threads
      • JustLikeThat
    • Go >
      • Tutorial
      • CodeSnippet
      • Go Routine_Channel
      • Suggestions
    • Methodologies & Design Patterns >
      • Design Principles
      • Design Patterns >
        • TemplatePattern
        • Adapter Design Pattern
        • Proxy
        • Lazy Initialization
        • CombinatorPattern
        • Singleton >
          • Singletons
        • Strategy
  • Frameworks
    • Apache Velocity
    • React Library >
      • Tutorial
    • Spring >
      • Spring Boot >
        • CustomProperties
        • ExceptionHandling
        • Custom Beans
        • Issues
      • Quick View
    • Rest WebServices >
      • Interviews
      • Swagger
    • Cloudera BigData >
      • Ques_Ans
      • Hive
      • Apache Spark >
        • ApacheSpark Installation
        • SparkCode
        • Sample1
        • DataFrames
        • RDDs
        • SparkStreaming
        • SparkFiles
    • Integration >
      • Apache Camel
    • Testing Frameworks >
      • JUnit >
        • JUnit Runners
      • EasyMock
      • Mockito >
        • Page 2
      • TestNG
    • Blockchain >
      • Ethereum Smart Contract
      • Blockchain Java Example
    • Microservices >
      • Messaging Formats
      • Design Patterns
    • AWS >
      • Honeycode
    • Dockers >
      • GitBash
      • Issues
      • Kubernetes
  • Databases
    • MySql
    • Oracle >
      • Interview1
      • SQL Queries
    • Elastic Search
  • Random issues
    • TOAD issue
    • Architect's suggestions
  • Your Views
Many times we get the issue to convert String to date or convert date from timezone to date of other timezone. Below is one way to get through such issues, I will cover some parts of Joda DateTime & other formats from SimpleDateFormat.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;


import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;


public class Conversions {

 public static void main(String[] args) {
  System.out.println("UTC Date String : " +
    toUTCString(new Date()));
  
  System.out.println("UTC Date : " +
  toUTCDate(new Date()));


  Date date = getDate(toUTCString(new Date()));
  System.out.println("Date from String : " + date);


  System.out.println("Date for TimeZone : " +
  toTimeZone(date, TimeZone.getTimeZone("Europe/Copenhagen")));
  System.out.println("Date for TimeZone : " +
  toTimeZone(date, TimeZone.getTimeZone("US/Alaska")));


  getTimeZonesList();

  //  Converting UTC date string to Date
  System.out.println("UTC Date from UTC Date String : " +
  toUTCString(getDate("Mon Dec 15 21:45:55 UTC 2014")));
 }


 /**
  * Converts given date to UTC date String
  * @param date
  * @return String
  */
 public static String toUTCString(Date date){


  SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
  final TimeZone utc = TimeZone.getTimeZone("UTC");
  dateFormatter.setTimeZone(utc);


  return dateFormatter.format(date);
 }


 /**
  * Converts given date to UTC date
  * @param date
  * @return Date
  */
 public static Date toUTCDate(Date date){


  SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
  TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
  dateFormatter.setTimeZone(TimeZone.getDefault());


  try {
   return dateFormatter.parse(dateFormatter.format(date));
  } catch (ParseException e) {
   e.printStackTrace();
  }
  return null;
 }


 /**
  * Coverts given date to date String in the given timezone
  * @param date
  * @param tz
  * @return String
  */
 public static String toTimeZone(Date date, final TimeZone tz){
  SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
  dateFormatter.setTimeZone(tz);


  return dateFormatter.format(date);
 }


 /**
  * Converts given date String to the Date type Object
  * @param date
  * @return Date
  */
 public static Date getDate(String date){
  SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
  try {
   return dateFormatter.parse(date);
  } catch (ParseException e) {
   e.printStackTrace();
  }


  return null;
 }


 /**
  * Returns the list of available TimeZone IDs supported
  * @return List<String>
  */
 public static List<String> getTimeZonesList(){
  List<String> ids = new ArrayList<>();


  String[] temp = TimeZone.getAvailableIDs();

  for(String id : temp){
   ids.add(id);
  }
  return Collections.unmodifiableList(ids);
 }
 
 /**
  * Converts XML Date to Util date format.
  *
  * @param XMLGregorianCalendar
  * @return java.util.Date
  */
  public static java.util.Date convertXMLDateToUtildate(
  final XMLGregorianCalendar date) {
  java.util.Date utilDate = null;
  TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
  if (date != null) {
  utilDate = date.toGregorianCalendar().getTime();
  }
  return utilDate;


  }

  /**
  * Converts date to XMLGregorianCalendar specific to collateral reply source
  * system.
  *
  * @param date
  * @return gregorianDate
  * @throws Exception
  */
  public static XMLGregorianCalendar convertToXMLGregorianDateFormat(
  final java.util.Date date) throws Exception {
  DatatypeFactory df = DatatypeFactory.newInstance();
  GregorianCalendar gc = new GregorianCalendar();
  // gc.setTimeZone(TimeZone.getTimeZone("UTC"));
  gc.setTimeInMillis(date.getTime());
  return df.newXMLGregorianCalendar(gc);
  }
}




Powered by Create your own unique website with customizable templates.