1
 public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
        try {
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
            DateTime date = formatter.parseDateTime(dateTime).withZoneRetainFields(DateTimeZone.UTC);
            return date.toString("h:mm aa");
        } catch (Exception e) {
            return null;
        }
    }

main(){
print(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"))
}

I am trying to convert given date-time in UTC format using joda date time it's giving wrong time it's given one hour before please help me what I am doing wrong.

The desired result is in London time, so 8:31 AM in this case.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
MARSH
  • 117
  • 1
  • 7
  • 22
  • Does this answer your question? [Parse ISO8601 date string to date with UTC Timezone](https://stackoverflow.com/questions/25938560/parse-iso8601-date-string-to-date-with-utc-timezone) – Alastair McCormack Apr 09 '20 at 08:02
  • Never hardcode `Z` as a literal in the format pattern string. It's an offset and needs to be oarsed as such. This is one likely reason for yoyr wrong time. – Ole V.V. Apr 09 '20 at 12:57
  • that is ok but when I try to convert current date-time then also I am getting wrong time in UTC I am getting one hour before can you please suggest how to get the current time in UTC – MARSH Apr 09 '20 at 13:01

4 Answers4

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

public class CurrentUtcDate {
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("UTC Time is: " + dateFormat.format(date));
    }
}

Output
UTC Time is: 22-01-2018 13:14:35

You can check here https://www.quora.com/How-do-I-get-the-current-UTC-date-using-Java

  • but I want in am h:mm aa format so I am getting wrong – MARSH Apr 09 '20 at 08:02
  • After getting time like this 22-01-2018 13:14:35 you can reformat it using SimpleDateFormat("hh:mm aa") https://stackoverflow.com/questions/1154903/why-does-parsing-2300-pm-with-simpledateformathhmm-aa-return-11-a-m – Okan Serdaroğlu Apr 09 '20 at 08:08
  • it's giving wrong my date-time is 2020-04-09T07:31:16Z while in output 22-01-2018 13:14:35 its wrong – MARSH Apr 09 '20 at 08:09
  • can you please help mee using joda date time because simple date for some API level depreciation is there – MARSH Apr 09 '20 at 08:13
  • No one asked for `Date` and `SimpleDateFormat`. And since they are poorly designed and long outdated, we should not suggest them. – Ole V.V. Apr 09 '20 at 12:59
0

As you need to you use Joda DateTime, you need to use formatter of Joda. You are returning date with pattern "h:mm aa" so I assume you need to extract time from the date.

Below code should work:

import java.util.Locale;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class MyDateCoonverter {

    public static void main(String a[]) {

        System.out.println(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"));
    }

    public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
            DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
            DateTime dt = formatter.parseDateTime(dateTime);
            return dt.toString("h:mm aa", Locale.ENGLISH);
    }
}

It gives output as: 7:31 AM

If you don't want to use any third party library & still want to extract only time from date, you can use Java's LocalTime.

Saurabhcdt
  • 1,010
  • 1
  • 12
  • 24
  • Providing Locale.ENGLISH is optional in dt.toString("h:mm aa", Locale.ENGLISH) – Saurabhcdt Apr 09 '20 at 08:27
  • buts it wrong because if you will check online compare with London time it will show 8.30 one hour before its showing using code I don't know where I am doing mistake – MARSH Apr 09 '20 at 08:32
  • For getting time with UTC timezone use withZone(DateTimeZone.UTC) e.g. DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").withZone(DateTimeZone.UTC); – Saurabhcdt Apr 09 '20 at 10:18
0

If you are using Java 8 or newer, you should not use java.util.Date (deprecated) or Joda Time (replaced by the new DATE API of Java 8 with java.time package) :

public static void main(String[] args) {
        String date = "2020-04-09T07:31:16Z";
        String formatedDate = ZonedDateTime.parse(date).format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT));
        System.out.println(formatedDate); //print "7:31 AM"
    }
}
Fabien
  • 974
  • 9
  • 14
  • but 7.31 am is wrong it should be 8.31 can you try with the current date and check its right or wrong – MARSH Apr 09 '20 at 08:37
  • 1
    If you want to convert the UTC time in Local time before formating you can use : String formatedDate = ZonedDateTime.parse(date).withZoneSameInstant(Clock.systemDefaultZone().getZone()).format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)); – Fabien Apr 09 '20 at 08:41
0

First, don’t handle date and time as strings in your program. Handle them as proper date-time objects. So but for all but the simplest throw-away programs you should not want a method that converts from a string in UTC to a string in London time in a different format.

So when you accept string input, parse into a DateTime object:

    String stringInput = "2020-04-09T07:31:16Z";
    DateTime dt = DateTime.parse(stringInput);
    System.out.println("Date-time is: " + dt);

Output so far is:

Date-time is: 2020-04-09T07:31:16.000Z

I am exploiting the fact that your string is in ISO 8601 format, the default for Joda-Time, so we need no explicit formatter for parsing it.

Not until you need to give string output, convert your date and time to the desired zone and format into the desired string:

    DateTimeZone zone = DateTimeZone.forID("Europe/London");
    DateTime outputDateTime = dt.withZone(zone);
    String output = outputDateTime.toString("h:mm aa");
    System.out.println("Output is: " + output);

Output is: 8:31 AM

What went wrong in your code

  1. Z in single quotes in your format pattern string is wrong. Z in your input string is an offset of 0 from UTC and needs to be parsed as an offset, or you are getting an incorrect result. Never put those quotes around Z.
  2. withZoneRetainFields() is the wrong method to use for converting between time zones. The method name means that the date and hour of day are kept the same and only the time zone changed, which typically leads to a different point in time.

What happened was that your string was parsed into 2020-04-09T07:31:16.000+01:00, which is the same point in time as 06:31:16 UTC, so wrong. You next substituted the time zone to UTC keeping the time of day of 07:31:16. This time was then formatted and printed.

Do consider java.time

As Fabien said, Joda-Time has later been replaced with java.time, the modern Java date and time API. The Joda-Time home page says:

Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161