Convert java.util.Date to String

前端 未结 18 2326
悲&欢浪女
悲&欢浪女 2020-11-22 05:37

I want to convert a java.util.Date object to a String in Java.

The format is 2010-05-30 22:15:52

相关标签:
18条回答
  • 2020-11-22 05:56
    Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String s = formatter.format(date);
    
    0 讨论(0)
  • 2020-11-22 05:59

    Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath)

    //Formats a date/time into a specific pattern
     DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
    
    0 讨论(0)
  • 2020-11-22 05:59

    One Line option

    This option gets a easy one-line to write the actual date.

    Please, note that this is using Calendar.class and SimpleDateFormat, and then it's not logical to use it under Java8.

    yourstringdate =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
    
    0 讨论(0)
  • 2020-11-22 06:01

    Why don't you use Joda (org.joda.time.DateTime)? It's basically a one-liner.

    Date currentDate = GregorianCalendar.getInstance().getTime();
    String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");
    
    // output: 2014-11-14 14:05:09
    
    0 讨论(0)
  • 2020-11-22 06:01

    Try this,

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    
    public class Date
    {
        public static void main(String[] args) 
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String strDate = "2013-05-14 17:07:21";
            try
            {
               java.util.Date dt = sdf.parse(strDate);         
               System.out.println(sdf.format(dt));
            }
            catch (ParseException pe)
            {
                pe.printStackTrace();
            }
        }
    }
    

    Output:

    2013-05-14 17:07:21
    

    For more on date and time formatting in java refer links below

    Oracle Help Centre

    Date time example in java

    0 讨论(0)
  • 2020-11-22 06:01
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = "2010-05-30 22:15:52";
        java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
        System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
    
    0 讨论(0)
提交回复
热议问题