1

I just need sample code block or suggestion to convert the following date string to utc time in format yyyy-MM-dd HH:mm:ss?

sample date string:11/23/2017 09:44am

there are similar questions like this but my test data is with am/pm.So pls dont consider this as duplicate

user2392695
  • 41
  • 1
  • 8
  • 1
    this should do it .----DateTimeFormatter.ofPattern("mm/dd/yyyy hh:mm a"); – priyadarshi swain Nov 24 '17 at 06:49
  • 2
    @priyadarshiswain "M" for month in year whereas "m" for "Minute in hour" – suvartheec Nov 24 '17 at 07:52
  • Possible duplicate of [Java8 DateTimeFormatter am/pm](https://stackoverflow.com/questions/38250379/java8-datetimeformatter-am-pm). I know you asked not to consider the question a duplicate, put the linked question has lowercase am/pm too, and the accepted answer solves that, so I fail to see why not. – Ole V.V. Nov 24 '17 at 12:10
  • @suvartheec Yes you are right, sorry for the typo. – priyadarshi swain Nov 24 '17 at 13:09
  • @OleV.V. That question is using other classes for the parsing/conversion. [This one](https://stackoverflow.com/q/18734452/1304575) is the exact as OP i would say – suvartheec Nov 25 '17 at 10:02
  • 1
    Possible duplicate of [Display current time in 12 hour format with AM/PM](https://stackoverflow.com/questions/18734452/display-current-time-in-12-hour-format-with-am-pm) – suvartheec Nov 25 '17 at 10:03
  • @suvartheec Thanks for contributing your duplicate suggestion. The OP didn’t use or ask for any specific classes. So what do you mean by “other classes”? The question you are linking to is asking about the long outdated `SimpleDateFormat` class and friends, mine about the modern `java.time` API. This question could be considered a duplicate of either. – Ole V.V. Nov 25 '17 at 10:13
  • 1
    @OleV.V. you are correct. I didnt notice the question was not about a particular library – suvartheec Nov 25 '17 at 10:18

4 Answers4

2

You could use the Java 8 time package:

String input = "11/23/2017 09:44am";
String format = "MM/dd/yyyy hh:mma";

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDateTime date = LocalDateTime.parse(input, formatter);
System.out.printf("%s%n", date);

But the problem is: this throws a DateTimeParseException, because of the lowercase 'am'.

I looked up in the docs, but I couldn't see a standard way to parse lowercase 'am' or 'pm' as as meridiem designator1. You'll end up manually replacing them:

input = input.replace("AM", "am").replace("PM","pm");

As mentioned by @OleVV in the comments, you can use a DateTimeFormatterBuilder and specify that the parsing should be case-insensitive:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
    .parseCaseInsensitive()
    .appendPattern(format)
    .toFormatter();

Then you can use this formatter as argument to the LocalDateTime.parse method.

Another answer of the aforementioned post provides a solution where you can override the AM/PM symbols with the lowercase variants.


1 Interestingly, the SimpleDateFormat does support the parsing of lowercase am/pm.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • Ways to handle the lowercase am/pm: (1) Simply convert the whole string to uppercase before parsing (since there are no other letters, this is harmless). (2) Use a `DateTimeFormatterBuilder` to either (a) simple: specify case insensitive parsing (b) specify literal strings to use for AM and PM. – Ole V.V. Nov 24 '17 at 12:07
  • I recommend you also give an explicit locale. AM and PM are called so in English, other langauges may have other names, so the code may not work on all computers with locale being specified. – Ole V.V. Nov 24 '17 at 18:40
0

SimpleDateFormat's javadoc lists all the options, including "a" for am/pm marker.

In you case, you need:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssa")
Yoav Gur
  • 1,366
  • 9
  • 15
0

The sample code below should do the conversion correctly.

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

public class DateConversion {

    public static void main(String[] argv) {

        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mma");
        SimpleDateFormat OutputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String sampleDateString = "11/23/2017 09:44am";

        try {
            Date convertDate = formatter.parse(sampleDateString);
            System.out.println(OutputFormatter.format(convertDate));

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

    }

}

This is to declare the date string to be parsed.

 SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mma");

and the output date as well

SimpleDateFormat OutputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Akjun
  • 351
  • 4
  • 13
0

At first you need to create a SimpleDateFormat with the proper pattern. This class helps you to parse your string to java.util.Date (more info here):

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma");

If your original string-date is in a special timezone then you need to instruct the parser to use this timezone:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma", Locale.ENGLISH);

Then you need to parse the string to date:

Date d = sdf.parse("11/23/2017 09:44am");

Finnaly you have to convert the timezoned date to UTC.

Please find bellow the full code snippet:

public static void main(String[] args) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma", Locale.ENGLISH);
    Date d = sdf.parse("11/23/2017 09:44am");
    System.out.println(toUtcZonedDateTime(d));
}

public static ZonedDateTime toUtcZonedDateTime(final Date date) {
    if (date == null) {
        return null;
    }

    final ZoneId utcZone = ZoneOffset.UTC;
    return ZonedDateTime.ofInstant(date.toInstant(), utcZone);
}

Output:

2017-11-23T08:44Z
zappee
  • 20,148
  • 14
  • 73
  • 129
  • Thanks for the solution.But i want the converted utc date to string.Is there any way to do it? – user2392695 Nov 24 '17 at 12:05
  • You have two options to convert java.util.Date to String. The first is to use the toString() method on the date vatiable. 2nd option is to create a SimpleDateFormat and use it: String dateStr = sdf.format(date) – zappee Nov 24 '17 at 15:29