简体   繁体   English

将日历字符串转换为Java中的Calendar对象

[英]Convert calendar String to Calendar Object in java

I wan't to convert a string Calendar Object (calendar.toString()) to calendar object. 我不会将字符串日历对象(calendar.toString())转换为日历对象。 I tried this solution but it show in console the date of the day '12-05-2017' not '02-02-2017' 我尝试了此解决方案,但它在控制台中显示的是日期'12 -05-2017'而不是'02 -02-2017'

String calendar object format: 字符串日历对象格式:

java.util.GregorianCalendar[time=1485993600000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Africa/Casablanca",offset=0,dstSavings=3600000,useDaylight=true,transitions=102,lastRule=java.util.SimpleTimeZone[id=Africa/Casablanca,offset=0,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=10800000,endTimeMode=0]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2017,MONTH=1,WEEK_OF_YEAR=5,WEEK_OF_MONTH=1,DAY_OF_MONTH=2,DAY_OF_YEAR=33,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=1,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=0,ZONE_OFFSET=0,DST_OFFSET=0] java.util.GregorianCalendar [time = 1485993600000,areFieldsSet = true,areAllFieldsSet = true,lenient = true,zone = sun.util.calendar.ZoneInfo [id =“ Africa / Casablanca”,offset = 0,dstSavings = 3600000,useDaylight = true,transitions = 102,lastRule = java.util.SimpleTimeZone [id = Africa / Casablanca,offset = 0,dstSavings = 3600000,useDaylight = true,startYear = 0,startMode = 2,startMonth = 2,startDay = -1,startDayOfWeek = 1,startTime = 7200000,startTimeMode = 0,endMode = 2,endMonth = 9,endDay = -1,endDayOfWeek = 1,endTime = 10800000,endTimeMode = 0]],firstDayOfWeek = 2,minimalDaysInFirstWeek = 4,ERA = 1, YEAR = 2017,MONTH = 1,WEEK_OF_YEAR = 5,WEEK_OF_MONTH = 1,DAY_OF_MONTH = 2,DAY_OF_YEAR = 33,DAY_OF_WEEK = 5,DAY_OF_WEEK_IN_MONTH = 1,AM_PM = 0,HOUR = 0,HOUR_OF_DAY = 0,MINUTE = 0,SECOND = 0,MILLISECOND = 0,ZONE_OFFSET = 0,DST_OFFSET = 0]

             Calendar calendar = GregorianCalendar.getInstance();
             calendar.setTime(new Date("2017/02/02"));
             System.out.println("calendar : "+calendar.getTime());
             try {
                 GregorianCalendar gc = new GregorianCalendar();
                 DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                 System.out.println("calendar : "+calendar.getTime());
                 gc.setTimeZone(TimeZone.getTimeZone(calendar.toString()));
                 System.out.println("tme zone : "+gc.getTimeZone());
                 System.out.println("calendar : "+calendar.getTime());
                 System.out.println("calendar : "+calendar.toString());
                 System.out.println(formatter.format(gc.getTime()));
             }
             catch(Exception e) {
                 //If exception, return server TimeStamp
             }

Any help please 任何帮助请

If that were me, I'd look at all the setters of both Calendar and GregorianCalendar and see if I thought I could extract the values needed for the setters from the string. 如果那是我,那么我将查看CalendarGregorianCalendar所有设置器,看看是否可以从字符串中提取设置器所需的值。 “time=1485993600000” should give you the most important information, the time, and you can feed it into setTimeInMillis() . “ time = 1485993600000”应该为您提供最重要的信息,时间,您可以将其输入setTimeInMillis() You ought to be able to get a time zone out of “Africa/Casablanca”. 您应该能够获得“非洲/卡萨布兰卡”之外的时区。 And so forth. 依此类推。 You can probably use regular expressions for extracting the fields from the string. 您可能可以使用正则表达式从字符串中提取字段。

You'd probably have to live with not covering all cases. 您可能不得不忍受没有涵盖所有情况。 Your particular GregorianCalendar seems to contain a sun.util.calendar.ZoneInfo and a java.util.SimpleTimeZone ; 您特定的GregorianCalendar似乎包含sun.util.calendar.ZoneInfojava.util.SimpleTimeZone I don't know whether that is always the case nor what other possibilities there are. 我不知道是否总是这样,还有其他可能性。

The strict test of your attempt is easy: just call toString() again on your newly constructed instance and see if you get the same string. 对您的尝试进行严格的测试很容易:只需在新构造的实例上再次调用toString()查看是否获得相同的字符串。 The difficulty comes if you accept some differences and you need to determine whether the actual differences lie within what you have decided to accept. 如果您接受一些差异,并且需要确定实际差异是否在您决定接受的范围之内,那么困难就来了。

Or really, I wouldn't want to bother if I could avoid it. 或者说真的,如果可以避免的话,我不想打扰。 I'd see if I could find an easier task or an easier way to obtain what you are really trying to obtain. 我想知道是否可以找到一个更轻松的任务或更轻松的方法来获取您真正想要获得的东西。 As I already said in a comment, one may use java.time.LocalDate instead of GregorianCalendar . 正如我在评论中已经说过的那样,可以使用java.time.LocalDate代替GregorianCalendar LocalDate.parse() will readily parse the string from LocalDate.toString() , and the problem is solved. LocalDate.parse()将容易地解析从字符串LocalDate.toString()和问题解决。 Just to give one example of another way to look at it. 仅举一个例子,以另一种方式来看待它。

In your code, you have two separate GregorianCalendar objects - one called calendar and one called gc . 在您的代码中,您有两个单独的GregorianCalendar对象-一个叫做calendar ,另一个叫做gc You're setting one calendar object to the date that you want, then printing out the other one. 您将一个日历对象设置为所需的日期,然后打印出另一个日历对象。

Thanks @Ole , I finally found the solution and it works. 感谢@Ole,我终于找到了解决方案,它可以工作。

             Calendar calendar = Calendar.getInstance();;
             calendar.setTime(new Date("2017/02/02"));
             String[] ds = calendar.toString().split("=");
             String[] ds2 = ds[1].split(",");
             try {
                 Calendar cal = Calendar.getInstance();;
                 DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
                 cal.setTimeInMillis(Long.valueOf(ds2[0]));
                 System.out.println(formatter.format(cal.getTime()));
             }
             catch(Exception e) {

             }

java.time java.time

You are using terrible old classes that are now supplanted by the much superior java.time classes. 您正在使用可怕的旧类,而现在这些类已经被更高级的java.time类所取代。

Instantiate a LocalDate . 实例化LocalDate The LocalDate class represents a date-only value without time-of-day and without time zone. LocalDate类表示没有日期和时区的仅日期值。

LocalDate ld = LocalDate.parse( "2017-02-02" ) ;

To generate a string in standard ISO 8601 format, call toString . 要生成标准ISO 8601格式的字符串,请调用toString

String output = ld.toString() ;

2017-02-02 2017-02-02

For other formats use the DateTimeFormatter class. 对于其他格式,请使用DateTimeFormatter类。

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;

02-02-2017 2017/02/02

Your Question is not clear. 您的问题不清楚。 If the problem is that your code is being handed a GregorianCalendar object, convert it to java.time.ZonedDateTime . 如果问题是您的代码正在传递给GregorianCalendar对象,请将其转换为java.time.ZonedDateTime Call new conversion methods added to the old classes. 调用添加到旧类中的新转换方法。

if( myCalendar instanceOf GregorianCalendar ) {
    ZonedDateTime zdt = myCalendar.toZonedDateTime() ;
}

Extract the date-only value you desire, as a LocalDate . 将所需的仅日期值提取为LocalDate

LocalDate ld = zdt.toLocalDate() ;

About java.time 关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于Java 8及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat . 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.DateCalendarSimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes. 现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial . 要了解更多信息,请参见Oracle教程 And search Stack Overflow for many examples and explanations. 并在Stack Overflow中搜索许多示例和说明。 Specification is JSR 310 . 规格为JSR 310

Where to obtain the java.time classes? 在哪里获取java.time类?

The ThreeTen-Extra project extends java.time with additional classes. ThreeTen-Extra项目使用其他类扩展了java.time。 This project is a proving ground for possible future additions to java.time. 该项目为将来可能在java.time中添加内容提供了一个试验场。 You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more . 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多

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

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