简体   繁体   English

我怎样才能得到简单的 yyyy-MM-dd 这个日期?

[英]How can i get simple yyyy-MM-dd out of this date?

I have String with date format dd.MM.yyyy, and I want to upload it to my MS SQL server, but the required format is yyyy-MM-dd.我有日期格式为 dd.MM.yyyy 的字符串,我想将其上传到我的 MS SQL 服务器,但所需的格式是 yyyy-MM-dd。 I tried this but it doesn't work like I want to.我试过这个,但它不像我想要的那样工作。

    String expDate = mDatePickerBtn.getText().toString();
    Date date = null;

    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
    try {
        date = format.parse(expDate);
        expDate = date.getYear() + "-" + date.getMonth() + "-" + date.getDay();
    } catch (ParseException e) {
        e.printStackTrace();
    }

For example if I pass 31.12.2032 to the expDate, the date variable will cointain "Fri Dec 31 00:00:00: GMT+01:00 2032", and the expDate will contain "132-11-5" and I don't even know why.例如,如果我将 31.12.2032 传递给 expDate,则日期变量将包含“Fri Dec 31 00:00:00: GMT+01:00 2032”,而 expDate 将包含“132-11-5”而我不甚至不知道为什么。 I would use DateTimeFormatter but my minimal API level is 24.我会使用 DateTimeFormatter,但我的最小 API 级别是 24。

My question is: where did I make mistake or how else can I get correct format out of this?我的问题是:我在哪里犯了错误,或者我怎么能从中得到正确的格式?

Go compile your app with Android Gradle Plugin 4.0.0+ and use java.time then like this: Go 使用 Android Gradle 插件 4.0.0+ 编译您的应用程序,然后像这样使用java.time

public static void main(String[] args) {
    // get / provide the String to be parsed
    String expDate = "31.12.2032";
    // provide a pattern that parses such a date
    String pattern = "dd.MM.uuuu";
    // create a DateTimeFormatter with this pattern
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern); 
    // parse the String with the DateTimeFormatter
    LocalDate expLocalDate = LocalDate.parse(expDate, dtf);
    // print the default format of a LocalDate
    System.out.println(expLocalDate);
    // print the LocalDate using the pattern created for parsing
    System.out.println(expLocalDate.format(dtf));
    // create a totally different DateTimeFormatter inline and format the date differently
    System.out.println(expLocalDate.format(DateTimeFormatter.ofPattern("EEE, dd 'of' MMMM uuuu",
                                                                        Locale.ENGLISH)));
}

The output would be this: output 将是这样的:

2032-12-31
31.12.2032
Fri, 31 of December 2032

Try this way试试这个方法

  String expDate = mDatePickerBtn.getText().toString();
    Date date = null;

    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
    try {
        date = format.parse(expDate);
        
        SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
        format1.format(date);
        
        expDate =  format1.format(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM