4

Hi I got date from third party REST service in string like 2014-10-14 03:05:39 which is in UTC format. How to convert this date into local format?

Mayank Pandya
  • 1,593
  • 2
  • 17
  • 40
  • 2
    You parse it in the UTC time zone, then format the result if you need to in the local time zone. What have you tried in order to do that? Are you able to use Joda Time or Java 1.8? – Jon Skeet Oct 16 '14 at 16:34
  • Thanks that is what i need. :-) I know joda time is better solution but I need to solve it without it. – Mayank Pandya Oct 16 '14 at 16:39
  • 1
    You should specify your requirements in the question then - there are three different "pretty popular" date/time libraries in Java: java.util.Calendar/Date, Joda Time, and java.time. If you're limited in terms of what you can use, please avoid wasting people's time by making that limitation clear as early as possible. – Jon Skeet Oct 16 '14 at 16:50
  • possible duplicate of [Joda time : How to convert String to LocalDate?](http://stackoverflow.com/questions/2721614/joda-time-how-to-convert-string-to-localdate) – Basil Bourque Oct 16 '14 at 19:22

2 Answers2

4

Try this:

import java.util.*;
import java.text.*;
public class Tester {
    public static void main(String[] args){
        try {
         String utcTimeString = "2014-10-14 03:05:39";

         DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
         Date utcTime = utcFormat.parse(utcTimeString);


         DateFormat localFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         localFormat.setTimeZone(TimeZone.getDefault());
         System.out.println("Local: " + localFormat.format(utcTime));

        } catch (ParseException e) {

        }

    }
}
MaxHeap
  • 1,138
  • 2
  • 11
  • 20
3

You can use LocalDate (Java 1.8) and the function LocalDateTime.parse

This function will return a LocalDateTime object based on the char sequence (your date) and a DateTimeFormatter.

From the Java 1.8 API:

public static LocalDateTime parse(CharSequence text,
                                  DateTimeFormatter formatter)

Obtains an instance of LocalDateTime from a text string using a specific formatter.
The text is parsed using the formatter, returning a date-time.

Parameters:
text - the text to parse, not null
formatter - the formatter to use, not null
Returns:
the parsed local date-time, not null
Throws:
DateTimeParseException - if the text cannot be parsed
rakke
  • 6,819
  • 2
  • 26
  • 28