Nitin Agrawal
Contact -
  • Home
  • Interviews
    • Secret Receipe
    • InterviewFacts
    • Resume Thoughts
    • Daily Coding Problems
    • BigShyft
    • CompanyInterviews >
      • InvestmentBanks >
        • ECS
        • Bank Of America
        • WesternUnion
        • WellsFargo
      • ProductBasedCompanies >
        • CA Technologies
        • Model N India
        • Verizon Media
        • Oracle & GoJek
        • IVY Computec
        • Nvidia
        • ClearWaterAnalytics
        • ADP
        • ServiceNow
        • Pubmatic
        • Expedia
        • Amphora
        • CDK Global
        • CDK Global
        • Epic
        • Sincro-Pune
        • Whiz.AI
        • ChargePoint
      • ServiceBasedCompanies >
        • Altimetrik
        • ASG World Wide Pvt Ltd
        • Paraxel International & Pramati Technologies Pvt Ltd
        • MitraTech
        • Intelizest Coding Round
        • EPAM
    • Interviews Theory
  • Programming Languages
    • Java Script >
      • Tutorials
      • Code Snippets
    • Reactive Programming >
      • Code Snippets
    • R
    • DataStructures >
      • LeetCode Problems
      • AnagramsSet
    • Core Java >
      • Codility
      • Program Arguments OR VM arguments & Environment variables
      • Java Releases
      • Threading >
        • ThreadsOrder
        • ProducerConsumer
        • Finalizer
        • RaceCondition
        • Executors
        • Future Or CompletableFuture
      • Important Points
      • Immutability
      • Dictionary
      • 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
        • Decorator
        • Proxy
        • Lazy Initialization
        • CombinatorPattern
        • RequestChaining
        • Singleton >
          • Singletons
  • Frameworks
    • Apache Velocity
    • Spring >
      • Spring Boot >
        • CustomProperties
        • ExceptionHandling
        • 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
  • 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.