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

更改Java字符串中的日期格式,java,string,date,formatting,date-format,Java,String,Date,Formatting,Date Format,我有一个表示日期的字符串 String date_s = "2011-01-18 00:00:00.0"; 我想将其转换为日期并以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

我有一个表示日期的
字符串

String date_s = "2011-01-18 00:00:00.0";
我想将其转换为
日期
并以
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
。我做错了什么?

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


附录:格式字符串中的“mm”与“mm”不同。使用MM表示月份,使用MM表示分钟。而且,yyyy与yyy不一样。e、 g.,:

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));
    }

}

[编辑以包括BalusC的更正] 全班同学应做到以下几点:

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();
}
使用(或者如果字符串恰好包含时区部分)将特定模式中的
字符串
解析为
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
格式化为
String

String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18
String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18
,当您还没有使用Java 8时,使用将特定模式中的
字符串
解析为
日期

String oldstring = "2011-01-18 00:00:00.0";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").parse(oldstring);
用于以特定模式将
日期
格式化为
字符串

String newstring = datetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(newstring); // 2011-01-18
String newstring = new SimpleDateFormat("yyyy-MM-dd").format(date);
System.out.println(newstring); // 2011-01-18
另见:


更新:根据您失败的尝试:模式区分大小写。阅读各部分所代表的含义。因此,代表月份的
M
,代表分钟的
M
。此外,年份是四位数的,而不是五位数的。请仔细查看我在上面发布的代码片段。

从格式中删除一个y,以便:

   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));
SimpleDateFormat dt1 = new SimpleDateFormat("yyyyy-mm-dd");
应该是:

SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
也可以使用子字符串()

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

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

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

时区 还有一个问题…你没有提到时区。如果你有意的话,那么你应该这么说。如果不是,则答案不完整。如果您想要的只是没有时间的日期部分,那么就没有问题了。但是,如果您做了可能涉及时间的进一步工作,那么您应该指定一个时区

乔达时间 下面是相同类型的代码,但使用的是第三方开源2.3库

/©2013巴西尔布尔克。此源代码可以由任何对此承担全部责任的人自由使用。
字符串日期=“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”);
//顺便说一下,如果您的日期时间字符串严格符合ISO 8601,包括“T”而不是空格“”,您可以
//使用Joda Time中内置的格式化程序,而不是指定自己的格式:ISODateTimeFormat.dateHourMinuteSecondFraction()。
//像这样:
//org.joda.time.DateTime dateTimeInUTC=org.joda.time.format.ISODateTimeFormat.dateHourMinuteSecondFraction().withZoneUTC().parseDateTime(日期);
//假设日期时间字符串是UTC(无时区偏移)。
org.joda.time.DateTime dateTimeInUTC=formatter.withZoneUTC().parseDateTime(日期);
System.out.println(“dateTimeInUTC:+dateTimeInUTC”);
System.out.println(“dateTimeInUTC(仅日期):”+org.joda.time.format.ISODateTimeFormat.date().print(dateTimeInUTC));
System.out.println(“”;//空行。
//假设日期-时间字符串位于加尔各答时区(以前称为加尔各答)。偏移距UTC为+5:30(注意半小时)。
org.joda.time.DateTimeZone kolkataTimeZone=org.joda.time.DateTimeZone.forID(“亚洲/加尔各答”);
org.joda.time.DateTime dateTimeInKolkata=formatter.withZone(加尔各答特区).parseDateTime(日期);
System.out.println(“dateTimeInKolkata:+dateTimeInKolkata”);
System.out.println(“dateTimeInKolkata(仅日期):”+org.joda.time.format.ISODateTimeFormat.date().print(dateTimeInKolkata));
//加尔各答的这个日期时间与上面创建的dateTimeInUTC实例在宇宙时间线上是不同的点。日期甚至不同。
System.out.println(“调整为UTC的dateTimeInKolkata:+dateTimeInKolkata.toDateTime(org.joda.time.DateTimeZone.UTC));
当运行时

dateTimeInUTC:2011-01-18T00:00:00.000Z
dateTimeInUTC(仅限日期):2011-01-18
dateTimeInKolkata:2011-01-18T00:00:00.000+05:30
dateTimeInKolkata(仅限日期):2011-01-18
dateTimeInKolkata调整为UTC:2011-01-17T18:30:00.000Z

使用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);

为什么不干脆用这个呢

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 yourDate = new Date();

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

它工作得很好

格式区分大小写,因此请使用MM表示月份,而不是MM(这表示分钟)和yyyy 因为你可以使用下面的备忘单

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

您可以尝试Java8new
date
,更多信息可在上找到

或者你可以试试旧的

publicstaticdategetdatefromstring(字符串格式,stringdatestr){
DateFormat formatter=新的SimpleDateFormat(格式);
日期=空;
试一试{
date=(date)formatter.parse(dateStr);
}捕获(解析异常){
e、 printStackTrace();
}
返回日期;
}
公共静态字符串getDate(日期日期,字符串日期格式){
DateFormat格式化程序=新的SimpleDataFormat(DateFormat);
返回格式化程序。格式(日期);
}
请参阅此处的“日期和时间模式”


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

从这个有趣的游戏中返回一个字符串
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
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();
    }
  } 

}
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;
    }
}
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
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;
}
String.valueOf(DateFormat.getDateInstance().format(new Date())));
/**
 * 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;
}