将字符串解析为数据并检索小时数

时间:2021-06-01 17:02:15

I am try to convert this string "2014-07-23 09:00:00" into something like this "9 PM". My code is:

我尝试将此字符串“2014-07-23 09:00:00”转换为类似“9 PM”的内容。我的代码是:

 public void printTime() {
        String data = "2014-07-23 09:00:00";
        SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.UK);
        SimpleDateFormat f2 = new SimpleDateFormat("ha",Locale.UK);
        Log.v(LOG, "Time is" + f2.format(f1.format(data)));
    }

But have this error:

但有这个错误:

Caused by: java.lang.IllegalArgumentException
    at java.text.DateFormat.format(DateFormat.java:365)
    at java.text.Format.format(Format.java:93)
    at launcher.alpentouch.com.myapplication.MainActivity.printTime(MainActivity.java:30)
    at launcher.alpentouch.com.myapplication.MainActivity.onCreate(MainActivity.java:21)
    at android.app.Activity.performCreate(Activity.java:5008)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
    at android.app.ActivityThread.access$600(ActivityThread.java:130) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
    at android.os.Handler.dispatchMessage(Handler.java:99) 
    at android.os.Looper.loop(Looper.java:137) 
    at android.app.ActivityThread.main(ActivityThread.java:4745) 
    at java.lang.reflect.Method.invokeNative(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:511) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
    at dalvik.system.NativeStart.main(Native Method)

 

4 个解决方案

#1


0  

Well i tried this:

我试过这个:

public static void main(String[] args) {
    String dateString = "2014-07-23 09:00:00";
    SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
    try {
        Date date = sdf.parse(dateString);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        System.out.println(calendar.get(Calendar.HOUR_OF_DAY) + " PM") ;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

9 PM

#2


2  

Don't fear to use the new Java 8 Time API so you don't run into problems like accidentally calling SimpleDateFormat.format(Object).

不要害怕使用新的Java 8 Time API,这样就不会遇到像意外调用SimpleDateFormat.format(Object)这样的问题。

String data = "2014-07-23 09:00:00";
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter destinationFormatter = DateTimeFormatter.ofPattern("h a");
String output = LocalDateTime.parse(data, sourceFormatter).format(destinationFormatter);

#3


1  

f2.format(f1.format(data))

makes no sense as you are trying to use a DateFormat to format a String. These objects parse Strings to Dates and format Dates to Strings. So instead you would use your DateFormat object to parse the String to a Date, and then format the result back to a String:

没有意义,因为您正在尝试使用DateFormat格式化String。这些对象将字符串解析为日期并将日期格式化为字符串。因此,您可以使用DateFormat对象将String解析为Date,然后将结果格式化为String:

f2.format(f1.parse(data))

When running into such errors, it's best to not try to make nested calls on one line since this will make it harder for you to find your error. So better:

遇到此类错误时,最好不要尝试在一行上进行嵌套调用,因为这会使您更难找到错误。好多了:

Date d = f1.parse(data);
String dateString = f2.format(d);

... at least until you fix the error. This way you'll know which part of your nested code is in error since the JVM will point directly to the offending line.

...至少在你修复错误之前。通过这种方式,您可以知道嵌套代码的哪一部分出错,因为JVM将直接指向违规行。

#4


0  

reading the date string you have, a think this is the ISO pattern (or a simplified form of it).
Using this code you will get what you want:

读取你拥有的日期字符串,认为这是ISO模式(或简化形式)。使用此代码,您将获得您想要的:

public void printTime(){
    // i think ISO allow a space between date and time, but our interpreter not
  String data = "2014-07-23 13:00:00";
  data = data.replace(' ', 'T'); // <<<---  Caution here!

  SimpleDateFormat f1 = new SimpleDateFormat("h a", Locale.UK);
  Calendar cad = javax.xml.bind.DatatypeConverter.parseDateTime(data);

  System.out.printf("Your format: %s \n", f1.format( cad.getTime() ) );
}

The javax.xml.bind.DatatypeConverter can parse this ISO pattern (with attention to the T between date and time), and with the calendar (and Date, calling .getTime() from Calendar) you can format to what you want.

javax.xml.bind.DatatypeConverter可以解析此ISO模式(注意日期和时间之间的T),并使用日历(和Date,从Calendar调用.getTime()),您可以格式化为您想要的格式。

But if you need a solution that receive a diferente type of date formatting you will need to be more specific regarding to this format.

但是,如果您需要一种接收不同类型日期格式的解决方案,则需要对此格式更具体。

One of the reasons to be using javax.xml.bind.DatatypeConverter here is that this parser can accept "diferent forms" of the ISO format. All these will be valid strings for that parser:
- "2014-07-23"
- "2014-07-23T13:00:00"
- "2014-07-23T13:00:00.100Z"

在这里使用javax.xml.bind.DatatypeConverter的原因之一是这个解析器可以接受ISO格式的“不同形式”。所有这些都是该解析器的有效字符串: - “2014-07-23” - “2014-07-23T13:00:00” - “2014-07-23T13:00:00.100Z”

Only with SimpleDateFormat you cannot parse the strings above, because SimpleDateFormat doesnt have a syntax flexible enough to declarer how to interpreter "different forms" of an input date string. So you end up with a solution that do checks on input string to define what is your SimpleDateFormat instance you need to use (maybe using RegExp to find the patterns on input string).

只有使用SimpleDateFormat才能解析上面的字符串,因为SimpleDateFormat没有足够灵活的语法来声明如何解释输入日期字符串的“不同形式”。因此,您最终得到一个解决方案,它对输入字符串进行检查,以定义您需要使用的SimpleDateFormat实例(可能使用RegExp查找输入字符串上的模式)。

#1


0  

Well i tried this:

我试过这个:

public static void main(String[] args) {
    String dateString = "2014-07-23 09:00:00";
    SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
    try {
        Date date = sdf.parse(dateString);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        System.out.println(calendar.get(Calendar.HOUR_OF_DAY) + " PM") ;
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

9 PM

#2


2  

Don't fear to use the new Java 8 Time API so you don't run into problems like accidentally calling SimpleDateFormat.format(Object).

不要害怕使用新的Java 8 Time API,这样就不会遇到像意外调用SimpleDateFormat.format(Object)这样的问题。

String data = "2014-07-23 09:00:00";
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter destinationFormatter = DateTimeFormatter.ofPattern("h a");
String output = LocalDateTime.parse(data, sourceFormatter).format(destinationFormatter);

#3


1  

f2.format(f1.format(data))

makes no sense as you are trying to use a DateFormat to format a String. These objects parse Strings to Dates and format Dates to Strings. So instead you would use your DateFormat object to parse the String to a Date, and then format the result back to a String:

没有意义,因为您正在尝试使用DateFormat格式化String。这些对象将字符串解析为日期并将日期格式化为字符串。因此,您可以使用DateFormat对象将String解析为Date,然后将结果格式化为String:

f2.format(f1.parse(data))

When running into such errors, it's best to not try to make nested calls on one line since this will make it harder for you to find your error. So better:

遇到此类错误时,最好不要尝试在一行上进行嵌套调用,因为这会使您更难找到错误。好多了:

Date d = f1.parse(data);
String dateString = f2.format(d);

... at least until you fix the error. This way you'll know which part of your nested code is in error since the JVM will point directly to the offending line.

...至少在你修复错误之前。通过这种方式,您可以知道嵌套代码的哪一部分出错,因为JVM将直接指向违规行。

#4


0  

reading the date string you have, a think this is the ISO pattern (or a simplified form of it).
Using this code you will get what you want:

读取你拥有的日期字符串,认为这是ISO模式(或简化形式)。使用此代码,您将获得您想要的:

public void printTime(){
    // i think ISO allow a space between date and time, but our interpreter not
  String data = "2014-07-23 13:00:00";
  data = data.replace(' ', 'T'); // <<<---  Caution here!

  SimpleDateFormat f1 = new SimpleDateFormat("h a", Locale.UK);
  Calendar cad = javax.xml.bind.DatatypeConverter.parseDateTime(data);

  System.out.printf("Your format: %s \n", f1.format( cad.getTime() ) );
}

The javax.xml.bind.DatatypeConverter can parse this ISO pattern (with attention to the T between date and time), and with the calendar (and Date, calling .getTime() from Calendar) you can format to what you want.

javax.xml.bind.DatatypeConverter可以解析此ISO模式(注意日期和时间之间的T),并使用日历(和Date,从Calendar调用.getTime()),您可以格式化为您想要的格式。

But if you need a solution that receive a diferente type of date formatting you will need to be more specific regarding to this format.

但是,如果您需要一种接收不同类型日期格式的解决方案,则需要对此格式更具体。

One of the reasons to be using javax.xml.bind.DatatypeConverter here is that this parser can accept "diferent forms" of the ISO format. All these will be valid strings for that parser:
- "2014-07-23"
- "2014-07-23T13:00:00"
- "2014-07-23T13:00:00.100Z"

在这里使用javax.xml.bind.DatatypeConverter的原因之一是这个解析器可以接受ISO格式的“不同形式”。所有这些都是该解析器的有效字符串: - “2014-07-23” - “2014-07-23T13:00:00” - “2014-07-23T13:00:00.100Z”

Only with SimpleDateFormat you cannot parse the strings above, because SimpleDateFormat doesnt have a syntax flexible enough to declarer how to interpreter "different forms" of an input date string. So you end up with a solution that do checks on input string to define what is your SimpleDateFormat instance you need to use (maybe using RegExp to find the patterns on input string).

只有使用SimpleDateFormat才能解析上面的字符串,因为SimpleDateFormat没有足够灵活的语法来声明如何解释输入日期字符串的“不同形式”。因此,您最终得到一个解决方案,它对输入字符串进行检查,以定义您需要使用的SimpleDateFormat实例(可能使用RegExp查找输入字符串上的模式)。