ChatGPT解决这个技术问题 Extra ChatGPT

更改 Java 字符串中的日期格式

我有一个代表日期的 String

String date_s = "2011-01-18 00:00:00.0";

我想将其转换为 Date 并以 YYYY-MM-DD 格式输出。

2011-01-18

我怎样才能做到这一点?

好的,根据我在下面检索到的答案,这是我尝试过的:

String date_s = " 2011-01-18 00:00:00.0"; 
SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss"); 
Date date = dt.parse(date_s); 
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
System.out.println(dt1.format(date));

但它输出 02011-00-1 而不是所需的 2011-01-18。我究竟做错了什么?

yyyyy 与 yyyy 不同。 :)
一个回旋镖问题。你的用例是什么?因为您可能应该使用内置模式 (DateFormat.getDateTimeInstance())。
月份在格式字符串中用 MM 表示,而不是像上面的示例中那样用 mm 表示。 mm 表示分钟。
我将 yyyy-mm-dd 更改为 yyyy-MM-dd,因为初始版本不起作用
“mm”是分钟数:)

C
Community

使用 LocalDateTime#parse()(如果字符串恰好包含时区部分,则使用 ZonedDateTime#parse())将特定模式中的 String 解析为 LocalDateTime

String oldstring = "2011-01-18 00:00:00.0";
LocalDateTime datetime = LocalDateTime.parse(oldstring, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"));

使用 LocalDateTime#format()(或 ZonedDateTime#format())以特定模式将 LocalDateTime 格式化为 String

String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18

或者,当您还没有使用 Java 8 时,使用 SimpleDateFormat#parse() 将特定模式的 String 解析为 Date

String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);

使用 SimpleDateFormat#format() 以特定模式将 Date 格式化为 String

String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18

也可以看看:

Java 字符串到日期的转换

更新:根据您的失败尝试:模式区分大小写。阅读java.text.SimpleDateFormat javadoc各个部分的含义。例如 M 代表月,m 代表分钟。此外,年份存在四位数 yyyy,而不是五位数 yyyyy。仔细查看我在上面发布的代码片段。


如果您希望日期看起来像“2012 年 9 月 1 日星期一”,该怎么办?
@crm:只需单击 javadoc 链接,在那里找出必要的模式字符并相应地更改模式。
如果您还没有使用 Java 8,请考虑使用反向移植 ThreeTen Backport,然后使用答案中的第一个示例。或者对于低于 API 级别 26 的 Android,ThreeTenABP
D
Dev

格式区分大小写,因此使用 MM 表示月份而不是 mm(这是分钟)和 yyyy 对于 Reference,您可以使用以下备忘单。

G   Era designator  Text    AD
y   Year    Year    1996; 96
Y   Week year   Year    2009; 09
M   Month in year   Month   July; Jul; 07
w   Week in year    Number  27
W   Week in month   Number  2
D   Day in year Number  189
d   Day in month    Number  10
F   Day of week in month    Number  2
E   Day name in week    Text    Tuesday; Tue
u   Day number of week (1 = Monday, ..., 7 = Sunday)    Number  1
a   Am/pm marker    Text    PM
H   Hour in day (0-23)  Number  0
k   Hour in day (1-24)  Number  24
K   Hour in am/pm (0-11)    Number  0
h   Hour in am/pm (1-12)    Number  12
m   Minute in hour  Number  30
s   Second in minute    Number  55
S   Millisecond Number  978
z   Time zone   General time zone   Pacific Standard Time; PST; GMT-08:00
Z   Time zone   RFC 822 time zone   -0800
X   Time zone   ISO 8601 time zone  -08; -0800; -08:00

例子:

"yyyy.MM.dd G 'at' HH:mm:ss z"  2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy"  Wed, Jul 4, '01
"h:mm a"    12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa"  02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z"    Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"   2001-07-04T12:08:56.235-0700
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"   2001-07-04T12:08:56.235-07:00
"YYYY-'W'ww-u"  2001-W27-3

“yyyy-MM-dd'T'HH:mm:ss.SSSZ”应该是“yyyy-MM-dd'T'HH:mm:ss.SSS'Z'”
不,如果你把 Z 放在单引号中,它会给出 Z 作为输出,但没有它会给出时区。例如。 2014-08-14T01:24:57.236Z 和没有它 2014-08-14T01:24:57.236-0530 --> 我试过 jdk1.7
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM 注意月份中的额外 M。四个不是五个!
如果是 4 个或更多字母,则使用完整形式。所以你可以使用 4 倍 m 甚至 5 倍 m 相同
这几乎是文档的复制粘贴。没有提供额外的解释,也没有指向文档的链接,如果需要可以获取更多信息。 -1。 (Here's the link btw)
H
Hovercraft Full Of Eels

答案当然是创建一个 SimpleDateFormat 对象并使用它来将字符串解析为日期并将日期格式化为字符串。如果您尝试过 SimpleDateFormat 但它不起作用,那么请显示您的代码以及您可能收到的任何错误。

附录:字符串格式中的“mm”与“MM”不同。用 MM 表示月,用 mm 表示分钟。此外,yyyyy 与 yyyy 不同。例如,:

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

public class FormateDate {

    public static void main(String[] args) throws ParseException {
        String date_s = "2011-01-18 00:00:00.0";

        // *** note that it's "yyyy-MM-dd hh:mm:ss" not "yyyy-mm-dd hh:mm:ss"  
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = dt.parse(date_s);

        // *** same for the format String below
        SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(dt1.format(date));
    }

}

导入 java.text.ParseException;导入 java.text.SimpleDateFormat;导入 java.util.Date; public class formateDate { /** * @param args * @throws ParseException */ public static void main(String[] args) throws ParseException { // TODO 自动生成的方法存根 String date_s=" 2011-01-18 00:00 :00.0"; SimpleDateFormat dt= new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");日期 date=dt.parse(date_s); SimpleDateFormat dt1=new SimpleDateFormat("yyyyy-mm-dd"); System.out.println(dt1.format(date));我想输出应该是“2011-01-18”但输出是 02011-00-1
发布您拥有的任何代码作为原始问题的补充(缩进四个空格)。这样它将保留其格式,然后我们可以阅读它。
请参阅上面对我的答案的编辑。您在格式字符串中使用“mm”,您应该使用“MM”
hh 将为您提供 1-12 范围内的小时,除了打印/解析 AMPM 之外,您还需要使用 a。要打印/解析 0-23 范围内的小时,请使用 HH
M
M--

为什么不简单地使用它

Date convertToDate(String receivedDate) throws ParseException{
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
        Date date = formatter.parse(receivedDate);
        return date;
    }

此外,这是另一种方式:

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String requiredDate = df.format(new Date()).toString();

或者

Date requiredDate = df.format(new Date());

为什么不使用这个?因为(a)它忽略了时区的问题。确定日期取决于时区。此代码取决于 JVM 的默认时区。因此,结果可能会在不经意间发生变化。 (b) 因为 java.util.Date 和 SimpleDateFormat 类是出了名的麻烦,应该避免使用。
总是返回字符串,Date requiredDate = df.format(new Date());
V
Vitalii Fedorenko

在 Java 8 及更高版本中使用 java.time 包:

String date = "2011-01-18 00:00:00.0";
TemporalAccessor temporal = DateTimeFormatter
    .ofPattern("yyyy-MM-dd HH:mm:ss.S")
    .parse(date); // use parse(date, LocalDateTime::from) to get LocalDateTime
String output = DateTimeFormatter.ofPattern("yyyy-MM-dd").format(temporal);

B
Bryan

[编辑以包括 BalusC 的更正] SimpleDateFormat 类应该可以解决问题:

String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
  Date date = format.parse("2011-01-18 00:00:00.0");
  System.out.println(date);
} catch (ParseException e) {
  e.printStackTrace();
}

DD 代表“一年中的一天”,而不是“一个月中的一天”。 hh 代表“上午/下午 (1-12) 中的小时”,而不是“一天中的小时 (0-23)”。
T
Touchstone

请参阅此处的“日期和时间模式”。 http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

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

public class DateConversionExample{

  public static void main(String arg[]){

    try{

    SimpleDateFormat sourceDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");

    Date date = sourceDateFormat.parse("2011-01-18 00:00:00.0");


    SimpleDateFormat targetDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(targetDateFormat.format(date));

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

}

B
Basil Bourque

其他答案是正确的,基本上你的模式中有错误数量的“y”字符。

时区

还有一个问题……您没有解决时区问题。如果您打算使用 UTC,那么您应该这么说。如果不是,则答案不完整。如果您想要的只是没有时间的日期部分,那么没问题。但是,如果您进行可能涉及时间的进一步工作,那么您应该指定一个时区。

乔达时间

这是相同类型的代码,但使用了第三方开源 Joda-Time 2.3 库

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.

String date_s = "2011-01-18 00:00:00.0";

org.joda.time.format.DateTimeFormatter formatter = org.joda.time.format.DateTimeFormat.forPattern( "yyyy-MM-dd' 'HH:mm:ss.SSS" );
// By the way, if your date-time string conformed strictly to ISO 8601 including a 'T' rather than a SPACE ' ', you could
// use a formatter built into Joda-Time rather than specify your own: ISODateTimeFormat.dateHourMinuteSecondFraction().
// Like this:
//org.joda.time.DateTime dateTimeInUTC = org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime( date_s );

// Assuming the date-time string was meant to be in UTC (no time zone offset).
org.joda.time.DateTime dateTimeInUTC = formatter.withZoneUTC().parseDateTime( date_s );
System.out.println( "dateTimeInUTC: " + dateTimeInUTC );
System.out.println( "dateTimeInUTC (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInUTC ) );
System.out.println( "" ); // blank line.

// Assuming the date-time string was meant to be in Kolkata time zone (formerly known as Calcutta). Offset is +5:30 from UTC (note the half-hour).
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
org.joda.time.DateTime dateTimeInKolkata = formatter.withZone( kolkataTimeZone ).parseDateTime( date_s );
System.out.println( "dateTimeInKolkata: " + dateTimeInKolkata );
System.out.println( "dateTimeInKolkata (date only): " + org.joda.time.format.ISODateTimeFormat.date().print( dateTimeInKolkata ) );
// This date-time in Kolkata is a different point in the time line of the Universe than the dateTimeInUTC instance created above. The date is even different.
System.out.println( "dateTimeInKolkata adjusted to UTC: " + dateTimeInKolkata.toDateTime( org.joda.time.DateTimeZone.UTC ) );

运行时…

dateTimeInUTC: 2011-01-18T00:00:00.000Z
dateTimeInUTC (date only): 2011-01-18

dateTimeInKolkata: 2011-01-18T00:00:00.000+05:30
dateTimeInKolkata (date only): 2011-01-18
dateTimeInKolkata adjusted to UTC: 2011-01-17T18:30:00.000Z

F
Fathah Rehman P
try
 {
    String date_s = "2011-01-18 00:00:00.0";
    SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    Date tempDate=simpledateformat.parse(date_s);
    SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");           
    System.out.println("Output date is = "+outputDateFormat.format(tempDate));
  } catch (ParseException ex) 
  {
        System.out.println("Parse Exception");
  }

c
cнŝdk

您可以使用:

Date yourDate = new Date();

SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
String date = DATE_FORMAT.format(yourDate);

它完美地工作!


此代码返回错误“未捕获的语法错误:意外的标识符”
@IvanFrolov 可能是您缺少导入,在哪一行出现错误?
哦,对不起 - 没有注意到它是 Java 的解决方案,我已经搜索了 javascript 的解决方案)))(顺便说一句 - 已经找到)。谢谢!
啊,好吧,现在很明显了。
R
Ralph
public class SystemDateTest {

    String stringDate;

    public static void main(String[] args) {
        SystemDateTest systemDateTest = new SystemDateTest();
        // format date into String
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
        systemDateTest.setStringDate(simpleDateFormat.format(systemDateTest.getDate()));
        System.out.println(systemDateTest.getStringDate());
    }

    public Date getDate() {
        return new Date();
    }

    public String getStringDate() {
        return stringDate;
    }

    public void setStringDate(String stringDate) {
        this.stringDate = stringDate;
    }
}

请在您的答案中添加一些信息以解释您的代码。
有一个方法名称 getDate() 通过它您可以在应用 SimpleDateFormat 之后获取日期 obj 以便您可以根据在 SimpleDateFormat 构造函数中定义并在 StringDate 方法中设置的格式转换日期,您可以将其缓存
E
Eren
   String str = "2000-12-12";
   Date dt = null;
   SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

    try 
    {
         dt = formatter.parse(str);
    }
    catch (Exception e)
    {
    }

    JOptionPane.showMessageDialog(null, formatter.format(dt));

M
Martin

您也可以使用 substring()

String date_s = "2011-01-18 00:00:00.0";
date_s.substring(0,10);

如果您想在日期前留一个空格,请使用

String date_s = " 2011-01-18 00:00:00.0";
date_s.substring(1,11);

A
Anbuselvan Rocky

您可以尝试 Java 8 新的date,更多信息可以在 Oracle documentation 上找到。

或者你可以试试旧的

public static Date getDateFromString(String format, String dateStr) {

    DateFormat formatter = new SimpleDateFormat(format);
    Date date = null;
    try {
        date = (Date) formatter.parse(dateStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return date;
}

public static String getDate(Date date, String dateFormat) {
    DateFormat formatter = new SimpleDateFormat(dateFormat);
    return formatter.format(date);
}

R
Radim Köhler
private SimpleDateFormat dataFormat = new SimpleDateFormat("dd/MM/yyyy");

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if(value instanceof Date) {
        value = dataFormat.format(value);
    }
    return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
};

M
M--

删除格式提供的一个 y 格式:

SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");

它应该是:

SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");

不完全是。您也需要正确的案例(无论您使用现代的 DateTimeFormatter 还是使用过时的 SimpleDateFormat)。
M
M--

我们可以将今天的日期转换为“2020 年 6 月 12 日”的格式。

String.valueOf(DateFormat.getDateInstance().format(new Date())));

R
Rajneesh Shukla
/**
 * Method will take Date in "MMMM, dd yyyy HH:mm:s" format and return time difference like added: 3 min ago
 *
 * @param date : date in "MMMM, dd yyyy HH:mm:s" format
 * @return : time difference
 */
private String getDurationTimeStamp(String date) {
    String timeDifference = "";

    //date formatter as per the coder need
    SimpleDateFormat sdf = new SimpleDateFormat("MMMM, dd yyyy HH:mm:s");
    TimeZone timeZone = TimeZone.getTimeZone("EST");
    sdf.setTimeZone(timeZone);
    Date startDate = null;
    try {
        startDate = sdf.parse(date);
    } catch (ParseException e) {
        MyLog.printStack(e);
    }

    //end date will be the current system time to calculate the lapse time difference
    Date endDate = new Date();

    //get the time difference in milliseconds
    long duration = endDate.getTime() - startDate.getTime();

    long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
    long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
    long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
    long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);

    if (diffInDays >= 365) {
        int year = (int) (diffInDays / 365);
        timeDifference = year + mContext.getString(R.string.year_ago);
    } else if (diffInDays >= 30) {
        int month = (int) (diffInDays / 30);
        timeDifference = month + mContext.getString(R.string.month_ago);
    }
    //if days are not enough to create year then get the days
    else if (diffInDays >= 1) {
        timeDifference = diffInDays + mContext.getString(R.string.day_ago);
    }
    //if days value<1 then get the hours
    else if (diffInHours >= 1) {
        timeDifference = diffInHours + mContext.getString(R.string.hour_ago);
    }
    //if hours value<1 then get the minutes
    else if (diffInMinutes >= 1) {
        timeDifference = diffInMinutes + mContext.getString(R.string.min_ago);
    }
    //if minutes value<1 then get the seconds
    else if (diffInSeconds >= 1) {
        timeDifference = diffInSeconds + mContext.getString(R.string.sec_ago);
    } else if (timeDifference.isEmpty()) {
        timeDifference = mContext.getString(R.string.now);
    }

    return mContext.getString(R.string.added) + " " + timeDifference;
}

A
Arvind Kumar Avinash

java.time

java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*

此外,下面引用的是来自 home page of Joda-Time 的通知:

请注意,从 Java SE 8 开始,用户被要求迁移到 java.time (JSR-310) - JDK 的核心部分,它取代了这个项目。

使用现代日期时间 API java.time 的解决方案:

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

public class Main {
    public static void main(String[] args) {
        String strDate = "2011-01-18 00:00:00.0";
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d H:m:s.S", Locale.ENGLISH);
        LocalDateTime ldt = LocalDateTime.parse(strDate, dtfInput);
        // Alternatively, the old way:
        // LocalDateTime ldt = dtfInput.parse(strDate, LocalDateTime::from);

        LocalDate date = ldt.toLocalDate();
        System.out.println(date);
    }
}

输出:

2011-01-18

ONLINE DEMO

关于解决方案的一些重要说明:

java.time 使得在 Date-Time 类型本身上调用解析和格式化函数成为可能,除了旧方式(即在格式化程序类型上调用解析和格式化函数,在 java.time API 的情况下是 DateTimeFormatter)。现代日期时间 API 基于 ISO 8601,并且不需要明确使用 DateTimeFormatter 对象,只要日期时间字符串符合 ISO 8601 标准,例如我没有使用 DateTimeFormatter 作为输出,因为 LocalDate#toString 已经返回所需格式的字符串。在这里,您可以使用 y 代替 u,但我更喜欢 u 而不是 y。

Trail: Date Time 了解有关现代日期时间 API 的更多信息。

* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project


p
pavel

假设您想将 2019-12-20 10:50 AM GMT+6:00 更改为 2019-12-20 10:50 AM 首先您必须了解日期格式第一个日期格式是 yyyy-MM-dd hh :mm a zzz 和第二个日期格式将是 yyyy-MM-dd hh:mm a

只需从此函数返回一个字符串,例如。

public String convertToOnlyDate(String currentDate) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a ");
    Date date;
    String dateString = "";
    try {
        date = dateFormat.parse(currentDate);
        System.out.println(date.toString()); 

        dateString = dateFormat.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return dateString;
}

此功能将返回您想要的答案。如果您想自定义更多,只需从日期格式中添加或删除组件。


E
Emad Aljumaily

你有一些错误: SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");

首先:应该是 new SimpleDateFormat("yyyy-mm-dd"); //yyyy 4 而不是 5 这个显示 02011,但是 yyyy 它显示 2011

第二:像这样更改您的代码new SimpleDateFormat("yyyy-MM-dd");

我希望能帮助你


M
M--
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");

这个日期时间类在几年前被现代 java.time 类所取代。特别是 DateTimeFormatterDateTimeFormatterBuilder。在 2019 年建议 SimpleDateFormat 是糟糕的建议。
不正确 您在此处的格式代码错误。 hh 为一小时。
通常我们期待一些讨论或解释。 Stack Overflow 不仅仅是一个片段库。