将java.util.Date转换为String

本文翻译自:Convert java.util.Date to String

I want to convert a java.util.Date object to a String in Java. 我想将java.util.Date对象转换为Java中的String

The format is 2010-05-30 22:15:52 格式为2010-05-30 22:15:52


#1楼

参考:https://stackoom.com/question/Nqb2/将java-util-Date转换为String


#2楼

Commons-lang DateFormatUtils is full of goodies (if you have commons-lang in your classpath) Commons-lang DateFormatUtils充满了好东西(如果你的类路径中有公共语言)

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");

#3楼

public static String formateDate(String dateString) {
    Date date;
    String formattedDate = "";
    try {
        date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
        formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return formattedDate;
}

#4楼

Why don't you use Joda (org.joda.time.DateTime)? 你为什么不用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

#5楼

public static void main(String[] args) 
{
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    System.out.println(form.format(d));
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that
}

#6楼

Altenative one-liners in plain-old java: 普通java中的单行代码:

String.format("The date: %tY-%tm-%td", date, date, date);

String.format("The date: %1$tY-%1$tm-%1$td", date);

String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);

String.format("The date and time in ISO format: %tF %<tT", date);

This uses Formatter and relative indexing instead of SimpleDateFormat which is not thread-safe , btw. 这使用Formatter相对索引而不是SimpleDateFormat ,它不是线程安全的 ,顺便说一句。

Slightly more repetitive but needs just one statement. 稍微多一点重复但只需要一个陈述。 This may be handy in some cases. 在某些情况下这可能很方便。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值