Add colon to 24 hour time in Java?

2.4k views Asked by At

I have a date in the format MM/DD/YYYY and time in the format HHMM (24 hour time w/o the colon). Both of these strings are in an array. I would like to store this as one string - maybe something like "MM-DD-YYYY HH:MM" - and then be able to convert it to a written date like "January 1, 2014 16:15" when I am showing it to the user. How can I do this?

This is the code that I have:

String date = "05/27/2014 23:01";
Date df = new SimpleDateFormat("MM/DD/YYYY HH:mm").parse(date);
System.out.println(df);

However this is what I get: "Sun Dec 29 23:01:00 EST 2013"

The output I am looking for is: "December 29, 2013 23:01"

7

There are 7 answers

0
Bharath On

You can use java.text.DateFormat class to convert date to string(format method), and string to date(parse method).

0
David S. On

You can use SimpleDateFormat both to parse Strings into dates and to format Dates back into Strings. Here's your example:

    SimpleDateFormat parser = new SimpleDateFormat("MM/DD/YYYY HH:mm");
    SimpleDateFormat formatter = new SimpleDateFormat("MMMM dd, yyyy HH:mm");

    String dateString = "05/27/2014 23:01";
    Date parsedDate = parser.parse(dateString);

    String formattedDateString = formatter.format(parsedDate);

    System.out.println("Read String '" + dateString + "' as '" + parsedDate + "', formatted as '" + formattedDateString + "'");

When I run this, I get:

Read String '05/27/2014 23:01' as 'Sun Dec 29 23:01:00 EST 2013', formatted as 'December 29, 2013 23:01'

0
Brian On

Goal

  1. Convert String to Date with the format you have it in
  2. Output that date as a String in the format you want

Code:

String date = "05/27/2014 23:01";
//convert the String to Date based on its existing format
Date df = new SimpleDateFormat("MM/dd/yyyy HH:mm").parse(date);
System.out.println("date  " +df); 
//now output the Date as a string in the format you want
SimpleDateFormat dt1 = new SimpleDateFormat("MMMM dd, yyyy HH:mm");
System.out.println(dt1.format(df));

Output:

date  Tue May 27 23:01:00 CDT 2014
May 27, 2014 23:01
0
StoopidDonut On

SimpleDateFormat is the way to go; to parse your Strings in the required meaningful date and time formats and finally print your date as a required String.

You specify the 2 formats as follows:

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");

Considering a simple hardcoded array of date and time (not the best way to show but your question calls it an array):

String[] array = { "12/31/2013", "1230" };

You would have to set these parsed dates in a Calendar instance:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, time.getHours());
cal.add(Calendar.MINUTE, time.getMinutes());

Finally format your date using the same SimpleDateFormat

SimpleDateFormat newFormat = new SimpleDateFormat("MMMM dd, yyyy 'at' hh:mm");

Here is the complete working code:

public class DateExample {
    public static void main(String[] args) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");

        String[] array = { "12/31/2013", "1230" };

        try {
            Date date = dateFormat.parse(array[0]);
            Date time = timeFormat.parse(array[1]);

            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.HOUR, time.getHours());
            cal.add(Calendar.MINUTE, time.getMinutes());

            SimpleDateFormat newFormat = new SimpleDateFormat(
                    "MMMM dd, yyyy 'at' hh:mm");
            String datePrint = newFormat.format(cal.getTime());

            System.out.println(datePrint);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

The output:

December 31, 2013 at 12:30

0
dhanushkac On

you can use this >>

    String s = sd.format(d);
    String s1 = sd1.format(d);

Here Is the full code >>

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

public class dt {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Date d = new Date();
    SimpleDateFormat sd = new SimpleDateFormat("MMMM dd, YYYY");
    SimpleDateFormat sd1 = new SimpleDateFormat("HH:mm");



            String s = sd.format(d);
        String s1 = sd1.format(d);

    System.out.println(s +" "+ s1);

}

}

0
Basil Bourque On

You should have bothered to do a bit of searching before posting. StackOverflow.com has many questions and answers like this already.

But for the sake of posterity, here's some example code using the Joda-Time 2.3 library. Avoid the java.util.Date/Calendar classes bundled with Java as they are badly designed and implemented. In Java 8, continue to use Joda-Time or switch to the new java.time.* classes defined by JSR 310: Date and Time API. Those new classes were inspired by Joda-Time but are entirely re-architected.

Joda-Time has many features aimed at formatting output. Joda-Time offers built-in standard (ISO 8601) formats. Some classes render strings with format and language appropriate to the host computer's locale, or you can specify a locale. And Joda-Time lets you define your own funky formats as well. Searching for "joda" + "format" will get you many examples.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

String input = "05/27/2014" + " " + "23:01";

Parse that string…

// Assuming that string is for UTC/GMT, pass the built-in constant "DateTimeZone.UTC".
// If that string was stored as-is for a specific time zone (NOT a good idea), pass an appropriate DateTimeZone instance.
DateTimeFormatter formatterInput = DateTimeFormat.forPattern( "MM/dd/yyyy HH:mm" ).withZone( DateTimeZone.UTC );
DateTime dateTime = formatterInput.parseDateTime( input );

Ideally you would store the values in an appropriate date-time format in a database. If not possible, then store as a string in ISO 8601 format, set to UTC/GMT (no time zone offset).

// Usually best to write out date-times in ISO 8601 format in the UTC time zone (no time zone offset, 'Z' = Zulu).
String saveThisStringToStorage = dateTime.toDateTime( DateTimeZone.UTC ).toString(); // Convert to UTC if not already in UTC.

Do your business logic and storage in UTC generally. Switch to local time zones and localized formatting only in the user-interface portion of your app.

// Convert to a localized format (string) only as needed in the user-interface, using the user's time zone.
DateTimeFormatter formatterOutput = DateTimeFormat.mediumDateTime().withLocale( Locale.US ).withZone( DateTimeZone.forID( "America/New_York" ) );
String showUserThisString = formatterOutput.print( dateTime );

Dump to console…

System.out.println( "input: " + input );
System.out.println( "dateTime: " + dateTime );
System.out.println( "saveThisStringToStorage: " + saveThisStringToStorage );
System.out.println( "showUserThisString: " + showUserThisString );

When run…

input: 05/27/2014 23:01
dateTime: 2014-05-27T23:01:00.000Z
saveThisStringToStorage: 2014-05-27T23:01:00.000Z
showUserThisString: May 27, 2014 7:01:00 PM
0
Arvind Kumar Avinash On

Unfortunately, none of the existing answers has mentioned the root cause of the problem which is as follows:

  • You have used D (which specifies Day in year) instead of d (Day in month).
  • You have used Y (which specifies Week year) instead of y (Year).

Learn more about it at the documentation page. Now that you have understood the root cause of the problem, let's focus on the solution using the best standard API of the time.

java.time

The legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.

I would solve it in the following steps:

  1. Parse the date string into LocalDate.
  2. Parse the time string into LocalTime.
  3. Combine the objects of LocalDate and LocalTime to obtain an object of LocalDateTime.
  4. Format the object of LocalDateTime into the desired pattern.

Demo using the modern API:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // 1. Parse the date string into `LocalDate`.
        DateTimeFormatter dateParser = DateTimeFormatter.ofPattern("M/d/u", Locale.ENGLISH);
        LocalDate date = LocalDate.parse("01/01/2014", dateParser);

        // 2. Parse the time string into `LocalTime`.
        DateTimeFormatter timeParser = DateTimeFormatter.ofPattern("HHmm", Locale.ENGLISH);
        LocalTime time = LocalTime.parse("1615", timeParser);

        // 3. Combine date and time to obtain an object of `LocalDateTime`.
        LocalDateTime ldt = date.atTime(time);

        // 4. Format the object of `LocalDateTime` into the desired pattern.
        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("MMMM d, uuuu HH:mm", Locale.ENGLISH);
        String output = dtfOutput.format(ldt);
        System.out.println(output);
    }
}

Output:

January 1, 2014 16:15

Learn more about the the modern date-time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.