2017-12-02 164 views
0

即时通讯从weeknumber创建日期,以及仅限于星期几。我已经成功完成了SimpleDateFormat,但我想将它保存为jodatime,我已经尝试了很多事情,但没有任何实际工作。将SimpleDateFormat解析为JodaTime

这是我的代码到目前为止。

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
Calendar cal = Calendar.getInstance(); 
cal.set(Calendar.WEEK_OF_YEAR, week_of_year); 
cal.set(Calendar.DAY_OF_WEEK, day_of_week); 
sdf.format(cal.getTime()); 

DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss"); 
DateTime jodatime = dtf.parseDateTime(sdf.toString()); 

我想得到一个jodatimeså,我的日历可以根据日期,时间安排对象进行排序。

当我运行的代码,并要显示的jodatime,我得到这个错误:

java.lang.IllegalArgumentException: Invalid format: "[email protected]" 
    at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:945) 
    at com.example.casper.autimeplan.Fragments.ScheduleFragment$MyJavaScriptInterface.getBasicInfo(ScheduleFragment.java:282) 
    at com.example.casper.autimeplan.Fragments.ScheduleFragment$MyJavaScriptInterface.access$400(ScheduleFragment.java:186) 
    at com.example.casper.autimeplan.Fragments.ScheduleFragment$MyJavaScriptInterface$1.run(ScheduleFragment.java:203) 

回答

0

你只是路过对象的toString这是行不通的。 尝试这样的事情

private static String parseDateTime(String input){ 
    String pattern = "MM/dd/yyyy HH:mm:ss"; 
    DateTime dateTime = DateTime.parse(input, DateTimeFormat.forPattern(pattern)); 
    return dateTime.toString("MM/dd/yyyy HH:mm:ss"); 
} 

更多here

1

TL;博士

LocalDate.now().with(WeekFields.ISO.weekOfWeekBasedYear(), weekOfYear) 
       .with(WeekFields.ISO.dayOfWeek(), dayOfWeek) 

java.time

不要使用旧麻烦日期时间类。此外,Joda-Time项目现在位于maintenance mode,建议迁移到java.time类。对于Android,请参阅下面最后一个项目符号中提到的ThreeTenABP项目。

您尚未定义您的周数。有很多方法可以定义一年的一周。我假定你的意思是第一周的标准ISO 8601定义为日历的第一个星期四,星期一是每周的第一天。使用WeekFields类,特别是WeekFields.ISO对象。

long weekOfYear = 27 ; // 1-52 or 1-53 for ISO 8601 week-based years. 
long dayOfWeek = 2 ; // 1-7 for Monday-Sunday, per ISO 8601 standard. 

LocalDate today = LocalDate.now(ZoneId.of("America/Montreal")) ; 
LocalDate adjusted = today.with(WeekFields.ISO.weekOfWeekBasedYear(), weekOfYear) 
          .with(WeekFields.ISO.dayOfWeek(), dayOfWeek) ; 

转储到控制台。

System.out.println("2017-W27-02: " + adjusted) ; 

2017-W27-02: 2017-07-04

看到这个code run live at IdeOne.com

顺便说一句...虽然没有移植到旧的Android,但其他Java平台可以使用ThreeTen-Extra库中的漂亮的YearWeek类进行此类工作。


关于java.time

java.time框架是建立在Java 8和更高版本。这些类取代了日期时间类legacy,如java.util.Date,Calendar,& SimpleDateFormat

Joda-Time项目现在位于maintenance mode,建议迁移到java.time类。请参阅Oracle Tutorial。并搜索堆栈溢出了很多例子和解释。规格是JSR 310

从何处获取java.time类?