want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format

后端 未结 10 1279
南旧
南旧 2020-11-22 01:31

I am using following code to get date in \"dd/MM/yyyy HH:mm:ss.SS\" format.

    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import          


        
相关标签:
10条回答
  • 2020-11-22 02:09

    If you are using JAVA8 API then this code will help.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String dateTimeString = LocalDateTime.now().format(formatter);
    System.out.println(dateTimeString);
    

    It will print the date in the given format.

    But if you again create a object of LocalDateTime it will print the 'T' in between the date and time.

    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter);
    System.out.println(dateTime.toString());
    

    So as mentioned in earlier posts as well, the representation and usage is different.

    Its better to use "yyyy-MM-dd'T'HH:mm:ss" pattern and convert the string/date object accordingly.

    0 讨论(0)
  • 2020-11-22 02:11

    Use:

     System.out.println("Current date in Date Format: " + sdf.format(date));
    
    0 讨论(0)
  • 2020-11-22 02:15

    The output in your first printline is using your formatter. The output in your second (the date created from your parsed string) is output using Date#toString which formats according to its own rules. That is, you're not using a formatter.

    The rules are as per what you're seeing and described here: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#toString()

    0 讨论(0)
  • 2020-11-22 02:16

    The following code gives expected output. Is that you want?

    import java.util.Calendar;
    import java.util.Date;
    
    public class DateAndTime {
    
        public static void main(String[] args) throws Exception {
            Calendar cal = Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SS");
            String strDate = sdf.format(cal.getTime());
            System.out.println("Current date in String Format: " + strDate);
    
            SimpleDateFormat sdf1 = new SimpleDateFormat();
            sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");
            Date date = sdf1.parse(strDate);
            String string=sdf1.format(date);
            System.out.println("Current date in Date Format: " + string);
    
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:18

    SimpleDateFormat

    sdf=new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
    String dateString=sdf.format(date);
    

    It will give the output 28/09/2013 09:57:19 as you expected.

    For complete program click here

    0 讨论(0)
  • 2020-11-22 02:19

    tl;dr

    • Use modern java.time classes.
    • Never use Date/Calendar/SimpleDateFormat classes.

    Example:

    ZonedDateTime                                // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone).
    .now(                                        // Capture the current moment.
        ZoneId.of( "Africa/Tunis" )              // Always specify time zone using proper `Continent/Region` format. Never use 3-4 letter pseudo-zones such as EST, PDT, IST, etc.
    )
    .truncatedTo(                                // Lop off finer part of this value.
        ChronoUnit.MILLIS                        // Specify level of truncation via `ChronoUnit` enum object.
    )                                            // Returns another separate `ZonedDateTime` object, per immutable objects pattern, rather than alter (“mutate”) the original.
    .format(                                     // Generate a `String` object with text representing the value of our `ZonedDateTime` object.
        DateTimeFormatter.ISO_LOCAL_DATE_TIME    // This standard ISO 8601 format is close to your desired output.
    )                                            // Returns a `String`.
    .replace( "T" , " " )                        // Replace `T` in middle with a SPACE.
    

    java.time

    The modern approach uses java.time classes that years ago supplanted the terrible old date-time classes such as Calendar & SimpleDateFormat.

    want current date and time

    Capture the current moment in UTC using Instant.

    Instant instant = Instant.now() ;
    

    To view that same moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.

    Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

    ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
    ZonedDateTime zdt = instant.atZone( z ) ;
    

    Or, as a shortcut, pass a ZoneId to the ZonedDateTime.now method.

    ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "Pacific/Auckland" ) ) ;
    

    The java.time classes use a resolution of nanoseconds. That means up to nine digits of a decimal fraction of a second. If you want only three, milliseconds, truncate. Pass your desired limit as a ChronoUnit enum object.

    ZonedDateTime
    .now( 
        ZoneId.of( "Pacific/Auckland" ) 
    )
    .truncatedTo(
        ChronoUnit.MILLIS
    )
    

    in “dd/MM/yyyy HH:mm:ss.SS” format

    I recommend always including the offset-from-UTC or time zone when generating a string, to avoid ambiguity and misunderstanding.

    But if you insist, you can specify a specific format when generating a string to represent your date-time value. A built-in pre-defined formatter nearly meets your desired format, but for a T where you want a SPACE.

    String output = 
        zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
        .replace( "T" , " " )  
    ;
    

    sdf1.applyPattern("dd/MM/yyyy HH:mm:ss.SS");

    Date date = sdf1.parse(strDate);

    Never exchange date-time values using text intended for presentation to humans.

    Instead, use the standard formats defined for this very purpose, found in ISO 8601.

    The java.time use these ISO 8601 formats by default when parsing/generating strings.

    Always include an indicator of the offset-from-UTC or time zone when exchanging a specific moment. So your desired format discussed above is to be avoided for data-exchange. Furthermore, generally best to exchange a moment as UTC. This means an Instant in java.time. You can exchange a Instant from a ZonedDateTime, effectively adjusting from a time zone to UTC for the same moment, same point on the timeline, but a different wall-clock time.

    Instant instant = zdt.toInstant() ;
    String exchangeThisString = instant.toString() ;
    

    2018-01-23T01:23:45.123456789Z

    This ISO 8601 format uses a Z on the end to represent UTC, pronounced “Zulu”.


    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

    You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android bundle implementations of the java.time classes.
      • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

    0 讨论(0)
提交回复
热议问题