获取java.lang.ClassCastException:java.lang.String无法强制转换为java.sql.Timestamp

时间:2016-09-28 05:48:03

标签: java

有问题的代码:

public static final String DATEFORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";

public static String getAsString(Object dateStr)
{

    if ( dateStr== null || dateStr.toString().equalsIgnoreCase("null"))
    {
        return null;
    }
    // here I am getting exception
    return (new SimpleDateFormat(DATEFORMAT)).format((Timestamp)dateStr);  
}

你能帮我避免课堂演出异常吗?

2 个答案:

答案 0 :(得分:2)

您可以使用函数- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. [self startRecognizer]; } - (void)startRecognizer { [SFSpeechRecognizer requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) { if (status == SFSpeechRecognizerAuthorizationStatusAuthorized) { SFSpeechRecognizer *sf =[[SFSpeechRecognizer alloc] init]; NSURL *mp3Path = [[NSBundle bundleForClass:[self class]] URLForResource:@"test" withExtension:@"mp3"]; SFSpeechURLRecognitionRequest *speechRequest = [[SFSpeechURLRecognitionRequest alloc]initWithURL:mp3Path]; [sf recognitionTaskWithRequest:speechRequest resultHandler:^(SFSpeechRecognitionResult * _Nullable result, NSError * _Nullable error) { NSString * translatedString = [[[result bestTranscription] formattedString] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSLog(@"%@",translatedString); }]; } }]; }

,而不是将字符串强制转换为时间戳

答案 1 :(得分:0)

你不能这样做,因为你不知道字符串中的内容是什么。也许你的代码中的datestr就像这样" abcdredsad"。如果你确定这个datestr对象是一个日期字符串,你只想更改格式化程序来自" yyyyMMdd HH:mm:ss"到" yyyy-MM-dd HH:mm:ss",试试这个。

public static void main(String[] args) {
    String date = StringToDate("20160928 15:00:00");
    System.out.println(date);
}

public static String StringToDate(Object datestr) {
    Date d = new Date();// note: set a default value here 
    Date date;      
    if (datestr == null)
        return null;    
    // you must know the old pattern of the datestr in your code
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
    try {
        d = sdf.parse(datestr.toString());// if your formatter is wrong, exception occurs here.
    } catch (ParseException e) {
        e.printStackTrace();
    }
    date = new Date(d.getTime());// if d didn't have a default value, wrong here.

    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    return sdf.format(date);
}