Search Results

Search found 32 results on 2 pages for 'jodatime'.

Page 1/2 | 1 2  | Next Page >

  • Difference between JodaTime and Calendar for years before 1900

    - by Yury Khrol
    I'm getting different values in milliseconds for the same date in past while using JodaTime lib and java.util.Calendar. For example for the first year AD void test() { int year = 1; DateTime dt = new DateTime(year, 1,1,0,0,0,0); dt = dt.toDateTime(GregorianChronology.getInstance()); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(year, 0, 1, 0, 0, 0); DateTime endDate = new DateTime(cal.getTimeInMillis()); endDate = endDate.toDateTime(GregorianChronology.getInstance()); System.out.println("JodaTime: " + dt); System.out.println("JodaTime, ms: " + dt.getMillis()); System.out.println("Calendar: " + cal.getTime()); System.out.println("Calendar, ms: " + cal.getTimeInMillis()); System.out.println("JodaTime by Calendar: " + endDate); } By default DateTime use ISOChronology and Calendar is GregorianCalendar (except TH and JA locales). So I set GregorianChronology, but nothing changed. Result of execution is JodaTime: 0001-01-01T00:00:00.000+01:34:52 JodaTime, ms: -62135602492000 Calendar: Sat Jan 01 00:00:00 EET 1 Calendar, ms: -62135776800000 JodaTime by Calendar: 0000-12-29T23:34:52.000+01:34:52 Could someone suggest am I wrong with something?

    Read the article

  • Occasional Date or timezone discrepancy in hudson or maven with jodatime

    - by TheStijn
    hi, I hope following explanation will make sense because it's a weird problem we're facing and hard to describe. We have a maven project which gets build in hudson and that contains some unit tests where dates are used and asserted. The hudson server runs on solaris. Now, occasionally (like 30% of the times) the unit tests using dates fail because 3,5 hours are deducted from the specified time in the unit test and hence asserts start failing. The other 70% everything works fine although nothing at all changed in the code and we run the hudson job several times an hour. I add following code to a unittest to check the time: @Test public void testDate() { System.out.println("new DateMidnight(2011, 1, 5).toDate();"); System.out.println(new DateMidnight(2011, 1, 5).toDate()); System.out.println(new DateMidnight(2011, 1, 5).toDate().getTime()); Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 2011); cal.set(Calendar.MONTH, 0); cal.set(Calendar.DAY_OF_MONTH, 5); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); System.out.println("cal.getTime();"); System.out.println(cal.getTime()); System.out.println(cal.getTime().getTime()); } So basically it should print the same thing when using jodatime or plain old Calendar. This is the case in 70% of the runs; for the other 30% I get following printouts: Running TestSuite new DateMidnight(2011, 1, 5).toDate(); Tue Jan 04 21:30:00 MET 2011 1294173000000 cal.getTime(); Wed Jan 05 12:00:00 MET 2011 1294225200000 Local maven tests never appear the pose this problem and we can't figure out what could be the cause of it. Especially, we can't think of a single reason why the tests sometimes pass and sometimes fail without changing any code nor hudson or server setting. Also, we run the maven install with cobertura which means that the unit tests are run twice. It happens also that they pass the first time and fail the second time or the other way around or that they fail both times. Thanks for any help, Stijn

    Read the article

  • JodaTime DateFormatter to display milliseconds if nonzero

    - by Mike
    I want to display a list of dates that may or may not have milliseconds on them. If a certain entry has milliseconds, then it should be displayed like yyyy MM dd HH:mm:ss.SSS. If it doesn't have the millis, I need it displayed as yyyy MM dd HH:mm:ss. I suppose the general question is: Is there a way to describe an optional format string parameter? (I'd like to avoid refactoring all of the places that I use formatters since this is a large code base.)

    Read the article

  • Library to work with date expressions in C#?

    - by ObligatoryMoniker
    What library can I use to calculate dates based on date expressions? A date expression would be something like: "+3D" (plus three days) "-1W" (minus one week) "-2Y+2D+1M" (minus 2 years, plus one day, plus one month) Example: DateTime EstimatedArrivalDate = CalcDate("+3D", DateTime.Now); Where estimated arrival date would equal the current date plus 3 days. I have heard about JodaTime and NodaTime but I have not seen anything in them yet that does this. What should I be using to get this functionality in C#?

    Read the article

  • Persisting Joda DateTime instead of Java Date in hibernate

    - by Tauren
    My entities currently contain java Date properties. I'm starting to use Joda Time for date manipulation and calculations quite frequently. This means that I'm constantly having to convert my Dates into Joda DateTime objects and back again. So I was wondering, is there any reason I shouldn't just change my entities to store Joda DateTime objects instead of Java Date objects? Please note that these entities are persisted via Hibernate. I found the jodatime-hibernate project, but I also was reading on the Joda mailing list that it wasn't compatible with newer versions of hibernate. And it seems like it isn't very well maintained. So I'm wondering if it would be best to just continue converting between Date and DateTime, or if it would be wise to start persisting DateTime objects. My concern is being reliant on a poorly maintained library. Edit: Note that one of my objectives is to be better able to store timezone information. Storing just a Date appears to save the date in the local timezone. As my application can be used globally, I need to know the timezone as well. Joda Time Hibernate seems to address this as well in the user guide.

    Read the article

  • How to find nearest week day for an arbitrary date?

    - by Stig Brautaset
    Is there a more elegant way than the below to find the nearest day of the week for a given date using JodaTime? I initially thought setCopy() would be it, but this sets the day to the particular day in the same week. Thus, if ld is 2011-11-27 and day is "Monday" the following function returns 2011-11-21, and not 2011-11-28 as I want. // Note that "day" can be _any_ day of the week, not just weekdays. LocalDate getNearestDayOfWeek(LocalDate ld, String day) { return ld.dayOfWeek().setCopy(day); } Below is a work-around I came up with that works for the particular constraints in my current situation, but I'd love to get help find a completely generic solution that works always. LocalDate getNearestDayOfWeek(LocalDate ld, String day) { LocalDate target = ld.dayOfWeek().setCopy(day); if (ld.getDayOfWeek() > DateTimeConstants.SATURDAY) { target = target.plusWeeks(1); } return target; } Looking more into this I came up with this, which seems to be a more correct solution, though it seems awfully complicated: LocalDate getNearestDayOfWeek(LocalDate ld, String day) { LocalDate target = ld.dayOfWeek().setCopy(day); if (target.isBefore(ld)) { LocalDate nextTarget = target.plusWeeks(1); Duration sincePrevious = new Duration(target.toDateMidnight(), ld.toDateMidnight()); Duration untilNext = new Duration(ld.toDateMidnight(), nextTarget.toDateMidnight()); if (sincePrevious.isLongerThan(untilNext)) { target = nextTarget; } } return target; }

    Read the article

  • Using Joda DateTime as a Jersey parameter?

    - by HolySamosa
    I'd like to use Joda's DateTime for query parameters in Jersey, but this isn't supported by Jersey out-of-the-box. I'm assuming that implementing an InjectableProvider is the proper way to add DateTime support. Can someone point me to a good implementation of an InjectableProvider for DateTime? Or is there an alternative approach worth recommending? (I'm aware I can convert from Date or String in my code, but this seems like a lesser solution). Thanks. Solution: I modified Gili's answer below to use the @Context injection mechanism in JAX-RS rather than Guice. import com.sun.jersey.core.spi.component.ComponentContext; import com.sun.jersey.spi.inject.Injectable; import com.sun.jersey.spi.inject.PerRequestTypeInjectableProvider; import java.util.List; import javax.ws.rs.QueryParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriInfo; import javax.ws.rs.ext.Provider; import org.joda.time.DateTime; /** * Enables DateTime to be used as a QueryParam. * <p/> * @author Gili Tzabari */ @Provider public class DateTimeInjector extends PerRequestTypeInjectableProvider<QueryParam, DateTime> { private final UriInfo uriInfo; /** * Creates a new DateTimeInjector. * <p/> * @param uriInfo an instance of {@link UriInfo} */ public DateTimeInjector( @Context UriInfo uriInfo) { super(DateTime.class); this.uriInfo = uriInfo; } @Override public Injectable<DateTime> getInjectable(final ComponentContext cc, final QueryParam a) { return new Injectable<DateTime>() { @Override public DateTime getValue() { final List<String> values = uriInfo.getQueryParameters().get(a.value()); if( values == null || values.isEmpty()) return null; if (values.size() > 1) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST). entity(a.value() + " may only contain a single value").build()); } return new DateTime(values.get(0)); } }; } }

    Read the article

  • Finding begin and end of year/month/day/hour

    - by reto
    I'm using the following snipped to find the begin and end of several time periods in Joda. The little devil on my left shoulder says thats the way to go... but I dont believe him. Could anybody with some joda experience take a brief look and tell me that the little guy is right? (It will be only used for UTC datetime objects) Thank you! /* Year */ private static DateTime endOfYear(DateTime dateTime) { return endOfDay(dateTime).withMonthOfYear(12).withDayOfMonth(31); } private static DateTime beginningOfYear(DateTime dateTime) { return beginningOfMonth(dateTime).withMonthOfYear(1); } /* Month */ private static DateTime endOfMonth(DateTime dateTime) { return endOfDay(dateTime).withDayOfMonth(dateTime.dayOfMonth().getMaximumValue()); } private static DateTime beginningOfMonth(DateTime dateTime) { return beginningOfday(dateTime).withDayOfMonth(1); } /* Day */ private static DateTime endOfDay(DateTime dateTime) { return endOfHour(dateTime).withHourOfDay(23); } private static DateTime beginningOfday(DateTime dateTime) { return beginningOfHour(dateTime).withHourOfDay(0); } /* Hour */ private static DateTime beginningOfHour(DateTime dateTime) { return dateTime.withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(0); } private static DateTime endOfHour(DateTime dateTime) { return dateTime.withMillisOfSecond(999).withSecondOfMinute(59).withMinuteOfHour(59); }

    Read the article

  • passing timezone from client (GWT) to server (Joda Time)

    - by Caffeine Coma
    I'm using GWT on the client (browser) and Joda Time on the server. I'd like to perform some DB lookups bounded by the day (i.e. 00:00:00 until 23:59:59) that a request comes in, with the time boundaries based on the user's (i.e. browser) timezone. So I have the GWT code do a new java.util.Date() to get the time of the request, and send that to the server. Then I use Joda Time like so: new DateTime(clientDate).toDateMidnight().toDateTime() The trouble of course is that toDateMidnight(), in the absence of a specified TimeZone, will use the system's (i.e. the server's) TimeZone. I've been trying to find a simple way to pass the TimeZone from the browser to the server without much luck. In GWT I can get the GMT offset with: DateTimeFormat.getFormat("Z").fmt(new Date()) which results in something like "-0400". But Joda Time's DateTimeZone.forID() wants strings formatted like "America/New_York", or an integer argument of hours and minutes. Of course I can parse "-0400" into -4 hours and 0 minutes, but I'm wondering if there is not a more straightforward way of doing this.

    Read the article

  • Joda time : convert string to LocatDate

    - by bsreekanth
    Hello, How to specify the format string to convert the date alone from string. In my case, only the date part is relevant Constructing it as DateTime fails String dateString = "2009-04-17"; DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime dateTime = formatter.parseDateTime(dateString); with error java.lang.IllegalArgumentException: Invalid format: "2011-04-17" is too short Probably because I should use LocalTime instead. But, I do not see any formatter for LocalTime . What is the best way to convert String dateString = "2009-04-17"; into LocalDate (or something else if that is not the right representation) thanks...

    Read the article

  • Joda time : DateTimeFormatter : beginning of a day

    - by bsreekanth
    Hello, DateTimeFormatter fmt = DateTimeFormat.forStyle('SS').withLocale(locale) DateTime dt = fmt.parseDateTime("11/4/03 8:14 PM"); the above statement will parse the string correctly, and save as DateTime (Joda Time). Now how to represent the beginning of a day. The below fails with DateTime dt = fmt.parseDateTime("11/4/03 00:01 AM"); Cannot parse "11/4/03 00:01 AM": Value 0 for clockhourOfHalfday must be in the range [1,12] I'm obviously confused with the standards, like what is the short representation of the beginning of a day. thanks.

    Read the article

  • Joda time : How to convert String to LocalDate?

    - by bsreekanth
    Hello, How to specify the format string to convert the date alone from string. In my case, only the date part is relevant Constructing it as DateTime fails: String dateString = "2009-04-17"; DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd"); DateTime dateTime = formatter.parseDateTime(dateString); with error java.lang.IllegalArgumentException: Invalid format: "2011-04-17" is too short Probably because I should use LocalDate instead. But, I do not see any formatter for LocalDate . What is the best way to convert String dateString = "2009-04-17"; into LocalDate (or something else if that is not the right representation) thanks...

    Read the article

  • Joda-Time: DateTime, DateMidnight and LocalDate usage

    - by fraido
    Joda-Time library includes different datetime classes DateTime - Immutable replacement for JDK Calendar DateMidnight - Immutable class representing a date where the time is forced to midnight LocalDateTime - Immutable class representing a local date and time (no time zone) I'm wondering how are you using these classes in your Layered Applications. I see advantages in having almost all the Interfaces using LocalDateTime (at the Service Layer at least) so that my Application doesn't have to manage Timezones and can safely assume Times always in UTC. My app could then use DateTime to manage Timezones at the very beginning of the Execution's Flow. I'm also wondering in which scenario can DateMidnight be useful.

    Read the article

  • How to convert string HH:MM to Joda Duration?

    - by Lucas T
    I have a field in a form to state the time duration of an event. Say, the event is to last 15 mins. So the field will have the following value: 00:15 If it is to last 1 hour: 01:00, etc. How can I create a Joda Duration object with the string "HH:MM"? Looking at Joda Time home page, it mentions that it is possible to create a Duration object from specified object using ConverterManager and DurationConverter respectively. My question is, how can I implement the above interfaces so that I can create a Duration object by passing the a "4:30" parameter? Thanks in advance, Lucas

    Read the article

  • Joda-Time: Period to string

    - by tt
    I'm using the Joda-Time library with Java. I'm having some difficulty trying to turn a Period object to a string in the format of "x days, x hours, x minutes". These Period objects are first created by adding an amount of seconds to them (they are serialized to XML as seconds and then recreated from them). If I simply use the getHours() etc. methods in them, all I get is zero and the total amount of seconds with getSeconds. How can I make Joda calculate the seconds into the respective fields, like days, hours, etc...?

    Read the article

  • Why Joda DateTimeFormatter cannot parse timezone names ('z')

    - by dimitrisli
    From DateTimeFormatter javadoc: Zone names: Time zone names ('z') cannot be parsed. Therefore timezone parsing like: System.out.println(new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse("Fri Nov 11 12:13:14 JST 2010")); cannot be done in Joda: DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss z yyyy"); System.out.println(dtf.parseDateTime("Fri Nov 11 12:13:14 JST 2010")); //Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "Fri Nov 11 12:13:14 JST 2010" is malformed at "JST 2010" //at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:673)

    Read the article

  • String to date (Invalid format)

    - by MrThys
    I am using Joda Time library to convert my String dates to a real date, because this seemed like the easiest solution to do this. I am using the DateTime object to do this; new DateTime(strValue); But when inserting some formats it throws me the exception; java.lang.IllegalArgumentException: Invalid format: "Mon, 30 Sep 2002 01:56:02 GMT" java.lang.IllegalArgumentException: Invalid format: "Sun, 29 Sep 2002 19:59:01 GMT" java.lang.IllegalArgumentException: Invalid format: "Mon, 30 Sep 2002 01:52:02 GMT" java.lang.IllegalArgumentException: Invalid format: "Sun, 29 Sep 2002 17:05:20 GMT" java.lang.IllegalArgumentException: Invalid format: "Sun, 29 Sep 2002 19:09:28 GMT" java.lang.IllegalArgumentException: Invalid format: "Sun, 29 Sep 2002 15:01:02 GMT" java.lang.IllegalArgumentException: Invalid format: "Sun, 29 Sep 2002 23:48:33 GMT" java.lang.IllegalArgumentException: Invalid format: "Sun, 29 Sep 2002 17:24:20 GMT" java.lang.IllegalArgumentException: Invalid format: "Sun, 29 Sep 2002 11:13:10 GMT" Is there a way to solve this, or should I use something else instead of DateTime.

    Read the article

  • How to query a date in HQL (Hibernate) with Joda Time?

    - by fabien7474
    I am sure that someone familiar with HQL (I am myself a newbie) can easily answer this question. In my Grails application, I have the following domain class. class Book { org.joda.time.DateTime releaseDate //I use the PersistentDateTime for persisting via Hibernate (that use a DATETIME type for MySQL DB) } In my HQL query, I want to retrieve books whose release date is included in range date1..date2 For instance I tried: DateTime date1, date2 ... def queryStr = "select * from Book as b where b.releaseDate > $date1 and b.releaseDate < $date2" def res = Book.executeQuery(queryStr) But I got the exception ...caused by: org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: The error token points to date format (for instance 2009-11-27T21:57:18.010+01:00 or Fri Nov 27 22:01:20 CET 2009) I have also tried to convert date1 into a Date class without success So what is the correct HQL code ? Should I convert to a specific format (which one?) using the patternForStyle method or is there another -cleaner- way to do it? Thanks, Fabien.

    Read the article

  • JODA time in Java Appengine

    - by aloo
    Has anyone gotten JODA time classes to work on Google Appengine? I'm using 1.3.4 of the java sdk and I get the following error when trying: java.lang.NoClassDefFoundError: com/google/appengine/repackaged/org/joda/time/DateTimeZone I've imported it as well: import com.google.appengine.repackaged.org.joda.time.DateTime;

    Read the article

  • Partially constructed object / Multi threading

    - by reto
    Heya! I'm using joda due to it's good reputation regarding multi threading. It goes great distances to make multi threaded date handling efficient, for example by making all Date/Time/DateTime objects immutable. But here's a situation where I'm not sure if Joda is really doing the right thing. It probably is correct, but I'd be very interested to see the explanation for it. When a toString() of a DateTime is being called Joda does the following: /* org.joda.time.base.AbstractInstant */ public String toString() { return ISODateTimeFormat.dateTime().print(this); } All formatters are thread safe, as they are as well ready-only. But what's about the formatter-factory: private static DateTimeFormatter dt; /* org.joda.time.format.ISODateTimeFormat */ public static DateTimeFormatter dateTime() { if (dt == null) { dt = new DateTimeFormatterBuilder() .append(date()) .append(tTime()) .toFormatter(); } return dt; } This is a common pattern in single threaded applications. I see the following dangers: Race condition during null check -- worst case: two objects get created. No Problem, as this is solely a helper object (unlike a normal singleton pattern situation), one gets saved in dt, the other is lost and will be garbage collected sooner or later. the static variable might point to a partially constructed object before the objec has been finished initialization (before calling me crazy, read about a similar situation in this Wikipedia article. So how does Joda ensure that not partially created formatter gets published in this static variable? Thanks for your explanations! Reto

    Read the article

  • Why does Joda time change the PM in my input string to AM?

    - by Tree
    My input string is a PM time: log(start); // Sunday, January 09, 2011 6:30:00 PM I'm using Joda Time's pattern syntax as follows to parse the DateTime: DateTimeFormatter parser1 = DateTimeFormat.forPattern("EEEE, MMMM dd, yyyy H:mm:ss aa"); DateTime startTime = parser1.parseDateTime(start); So, why is my output string AM? log(parser1.print(startTime)); // Sunday, January 09, 2011 6:30:00 AM

    Read the article

  • Rounding up milliseconds when printing with Joda Time

    - by RoToRa
    I'm implementing a count-down using Joda Time. I only need a display accuracy of seconds. However when printing the time, the seconds are displayed as full seconds, so when the count down reaches, for example, 900ms, then "0" seconds is printed, but as a count-down it would make more sense to display "1" second, until the time actually reaches 0ms. Example: void printDuration(Duration d) { System.out.println( d.toPeriod(PeriodType.time()).toString( new PeriodFormatterBuilder().printZeroAlways().appendSeconds().toFormatter() ) ); } printDuration(new Duration(5000)); // Prints "5" => OK printDuration(new Duration(4900)); // Prints "4" => need "5" printDuration(new Duration(1000)); // Prints "1" => OK printDuration(new Duration(900)); // Prints "0" => need "1" printDuration(new Duration(0)); // Prints "0" => OK Basically I need to the seconds to be display rounded up from milliseconds and not rounded down. Is there a way to achieve this with Joda without needing to write my own formatter?

    Read the article

  • Joda Time cannot subtract one hour

    - by Leoa
    In my android program, I have a spinner that allows the user to select different times. Each selection is processed with Joda time to subtract the minutes. It works fine for minutes 0 to 59 and 61 and greater. However, when 60 minutes is subtracted, the time is not updated, and the original time is shown. How do I get Joda time to subtract 60 minutes? Spinner: public class MyOnItemSelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView<?> parent, View view, int pos, long id1) { String mins = parent.getItemAtPosition(pos).toString(); int intmins=0; // process user's selection of alert time if(mins.equals("5 minutes")){intmins = 5;} if(mins.equals("10 minutes")){intmins = 10;} if(mins.equals("20 minutes")){intmins = 20;} if(mins.equals("30 minutes")){intmins = 30;} if(mins.equals("40 minutes")){intmins = 40;} if(mins.equals("50 minutes")){intmins = 50;} if(mins.equals("60 minutes")){intmins = 60;} if(mins.equals("120 minutes")){intmins = 120;} String stringMinutes=""+intmins; setAlarm(intmins, stringMinutes); } else { } public void onNothingSelected(AdapterView parent) { mLocationDisplay.setText(" " + location); } } public void setAlarm(int intmins, String mins) { // based alarm time on start time of event. TODO get info from database. String currentDate; SimpleDateFormat myFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date date1 = null; DateTime dt; currentDate = eventdate + " " + startTimeMilitary;// startTimeMilitary; try { date1 = myFormat.parse(currentDate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } dt = new DateTime(date1); long dateInMillis = dt.getMillis(); String sDateInMillis = Long.toString(dateInMillis); // subtract the selected time from the event's start time String newAlertTime = subtractTime(dt, intmins); newAlertTime = subtractTime(dt, intmins); //......}

    Read the article

1 2  | Next Page >