Hot questions for Using Joda-Time in timestamp

Question:

How do I convert a org.joda.time.LocalDateTime to an Unix timestamp, given that local time is in UTC timezone?

Example:

new LocalDateTime(2015, 10, 02, 11, 31, 40) > 1443785500.


Answer:

Given that you want the Unix timestamp "the given LocalDateTime, in UTC" the simplest approach is just to convert it to a DateTime by specifying the DateTimeZone for UTC, and convert that:

LocalDateTime local = new LocalDateTime(2015, 10, 02, 11, 31, 40);
DateTime utc = local.toDateTime(DateTimeZone.UTC);
long secondsSinceEpoch = utc.getMillis() / 1000;

Note the use of seconds here as a Unix timestamp - other APIs (e.g. java.util.Date) may expect milliseconds since the Unix epoch.

Question:

"timestamp_utc": "۲۰۱۵-۱۱-۰۲T۱۸:۴۴:۳۴+۰۰:۰۰"

is an attribute in a JSON. How do I parse this date? I tried the following piece of code.

try 
{
    return new DateTime(dateStr, DateTimeZone.UTC);
}
catch (IllegalArgumentException e)
{
    java.util.Locale locale = new java.util.Locale( "ar", "SA" );
    DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withLocale( locale );
    return formatter.parseDateTime( dateStr );
}

2015-05-11T11:31:47 Works just fine. However, ۲۰۱۵-۱۱-۰۲T۱۸:۴۴:۳۴+۰۰:۰۰ throws an IllegalArgumentException. Tried parsing the date with other locales/formats as well. No luck.

Locale list[] = DateFormat.getAvailableLocales();
        for (Locale aLocale : list) {
            try{
                DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ssZ" ).withLocale(aLocale);
                System.out.println(formatter.parseDateTime( dateStr ));
            }
            catch(Exception e){
                System.out.println("locale " + aLocale.toString() + " error");
            }
        }

Please help me out.


Answer:

Adding a non-Arabic character (T) made it a non-Arabic date (I got the idea by trying to translate it in google translate). Try the below (Changed T to <space> in both input date and the pattern):

public static void main (String[] args) throws java.lang.Exception
{
    String ara = "۲۰۱۵-۱۱-۰۲ ۱۸:۴۴:۳۴+۰۰:۰۰";
    for (Locale aLocale : DateFormat.getAvailableLocales()) {
        //Just to save time, not needed.
        if(aLocale.getLanguage() != "ar") continue;
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+SS:SS", aLocale);
            System.out.println(sdf.parse( ara ));
        }
        catch(Exception e){
            System.out.println("locale " + aLocale.toString() + " error");
        }
    }
}

Question:

I'm trying to do a timestamp validation using joda time-1.6.2. Please point my error and help me out. Code

String timestamp = "2014-09-23T23:03:11Z";
String datePattern = "yyyy-MM-dd'T'HH:mm:ssZ";

try {
             DateTimeFormatter dateFormatter = DateTimeFormat.forPattern(datePattern);
             dateFormatter.parseDateTime(timestamp);

        } catch (Exception e) {
            LOG.info("Timestamp is invalid format" + e);
        }

Exception

INFO: Timestamp is invalid formatjava.lang.IllegalArgumentException: Invalid format: "2014-09-23T23:03:11Z" is malformed at "Z"

Answer:

I am very sceptical about treating Z just as literal. The char Z has a meaning, namely zero offset. The documentation of Joda-Time version 1.6 says about this code:

String timestamp = "2014-09-23T23:03:11Z";
DateTime dt = 
  ISODateTimeFormat.dateTimeNoMillis().parseDateTime(timestamp).withZone(DateTimeZone.UTC);
System.out.println(dt); // 2014-09-23T23:03:11.000Z

Returns a formatter that combines a full date and time without millis, separated by a 'T' (yyyy-MM-dd'T'HH:mm:ssZZ). The time zone offset is 'Z' for zero, and of the form '±HH:mm' for non-zero.

Now let's view at following four alternatives in detail (explicitly tested with version 1.6.2):

String timestamp = "2014-09-23T23:03:11Z";
DateTimeZone utc = DateTimeZone.UTC;

DateTime dt1 = ISODateTimeFormat.dateTimeNoMillis().parseDateTime(timestamp).withZone(utc);
System.out.println(dt1); // 2014-09-23T23:03:11.000Z (OK)

DateTime dt2 = new DateTime(timestamp, utc);
System.out.println(dt2); // 2014-09-23T23:03:11.000Z (OK)

DateTime dt3 =
  DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").parseDateTime(timestamp).withZone(utc);
System.out.println(dt3); //2014-09-23T21:03:11.000Z (WRONG!!!)

DateTime dt4 =
  DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZZ").parseDateTime(timestamp).withZone(utc);
// exception: Invalid format: "2014-09-23T23:03:11Z" is malformed at "Z"

Conclusion: The other answers given so far treating Z as literal are wrong because the input is treated in local timezone, not with offset UTC+00:00. Use either the constructor or the specific class IsoDateTimeFormat (I would prefer latter one for clarity).

About the exception: This is a bug solved with version 2.0, see release-notes. You should better update your library version.

Allow 'Z' and 'ZZ' in format patterns to parse 'Z' as '+00:00' [2827359]

Question:

Is this possible? I found a few solution for converting to and from localDateTime like can be seen here

But I can't find a solution for Joda Instant...


Answer:

You can use the epoch millis to convert:

Timestamp ts = ....;
Instant i = new Instant(ts.getTime());
Timestamp ts2 = new Timestamp(i.getMillis());

Question:

Somewhere in the code I have Timestamp ts = Timestamp.from(instant); where instant is, as the name suggests, java.time.Instant. (Why? To allow Hibernate 4.x to persist, via a UserType, JDK8 time types, not yet supported before Hibernate 5).

In fact, let me put the code so it's clear. The log statement is for this problem.

public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException {
    if (value != null){
        Timestamp ts = Timestamp.from((Instant) value);
        log.info("nullSafeSet from " + value + " (as long: " + ((Instant) value).toEpochMilli() + ") to " + ts + " (as long: " + ts.getTime() + ")");
        StandardBasicTypes.TIMESTAMP.nullSafeSet(st, ts, index, session);
    } else {
        st.setNull(index, Types.TIMESTAMP);
    }
}

And here's the problem. On Windows (7, 64-bit although it shouldn't matter) the string representation of the Timestamp corresponds to the UTC value.

From: 2015-05-12T19:00:08.191Z (as long: 1431457208191) 
  to: 2015-05-12 19:00:08.191  (as long: 1431457208191)

On *nix (Linux, OS X), the string representation corresponds to the local (EST, or EDT to be precise) time:

From: 2015-05-12T19:16:54.488Z (as long: 1431458214488) 
  to: 2015-05-12 15:16:54.488  (as long: 1431458214488)

The absolute times are the same as it can be seen. The problem is that what the JDBC driver sends to an Oracle database into a TIMESTAMP field is the string representation or an equivalent (I looked at the network traffic, the parameter is in binary format so it's not easy to figure out exactly what gets sent). The same code inserts the UTC equivalent of the time when executed from Windows and the local time when executed from Unix.

I already checked the user.timezone system property, it's America/New York in both cases. Also the machines themselves are so. Same JDK8 version, same app server, same code.

I'm puzzled by the behaviour and how to fix it.


Answer:

Well, eventually I tracked the cause down and it's different than what I thought. Thanks to @JBNizet for the tip that sent me on the right path.

As mentioned in the comment, by the time the particular method got executed, one one system TimeZone.getDefault() was returning "UTC" on Windows and "America/New York" on the Unix machine. Even though both systems started with user.timezone="America/New York", confirmed by logging.

The real cause was that on the Windows machine, I also had a different web application deployed in the same server. That application, written in Grails, was calling TimeZone.setDefault("UTC"), thus overriding, at JVM level, the time zone set via the property in my app. I confirmed this with a breakpoint in TimeZone.setDefault().

Question:

My user picks a date, which I store in epoch seconds (or milliseconds if necessary).

Separately my user picks a time of day and a timezone.

How do I adjust my epoch time with this new information. I feel like I should be able to add X milliseconds based on the hour/minute and then subtract based on the UTC offset of the timezone, but maybe there is a method that does this for me already


Answer:

In Java, you should perform date and time manipulation via a java.util.Calendar instance. You can use that for datetime storage, as well. Exactly how you would proceed depends on the form of the input and the desired form of the output, but it might go something like this:

public long computeDateTimeMillisUTC(long dateMillisUTC, int hour24,
        int minute, TimeZone zone) {
    Calendar cal = Calendar.getInstance(zone);

    cal.setTimeInMillis(dateMillisUTC);
    cal.set(Calendar.HOUR_OF_DAY, hour24);
    cal.set(Calendar.MINUTE, minute);

    return cal.getTimeInMillis();
}

Question:

I would like to know if a particular date belongs to:

Spring Summer Fall Winter

This is how I am initializing the DateTime

DateTimeZone timeZone = DateTimeZone.forID("America/Los_Angeles");
timestamp = new DateTime(unixtimestamp, timeZone);

Is it possible using JodaTime?

I found a similar post which is useful but it doesn't take the Hemisphere in to acccount:

Identifying the season from the Date using Java


Answer:

No, joda time does not provide this functionality. It provides you info about time which has to do with how much the earth is rotated on its axis. Seasons have to do with the earth's rotation relative to the sun. So even though "Los Angeles" is in the northern hemisphere, Joda time doesn't know that. It only knows that its time zone is UTC-08:00 which exists in both hemispheres.

Luckily the earth spins (reasonably) predictably and cyclically around the sun. So at any time you can determine the season for a given time and Hemisphere. In the referenced stack overflow they basically fixed the hemisphere so that the only two variables where time and season.

If you want to take into consideration the hemisphere you can use the existing solution and at the end write a function that will invert the season if your location is in the southern hemisphere instead of the northern hemisphere.

Solution left to the reader as an exercise

Question:

I am using the following method to return a formatted date as say 07:00AM, Apr 12 2016. But I keep getting 01:41PM, Sat, Jan 17 1970. Say for example my timestamp is 1460469600.

Here is my method.

public static String formattedDate(long timestamp) {
    DateTime date = new DateTime(timestamp);
    String formatted= date.toString("hh:mma, EEE, MMM dd yyyy");
    return formatted;
}

Answer:

Your timeStamp is wrong. It doesnt represent the correct time in millis. YOur timeStamp refers to 01:41PM, Sat, Jan 17 1970.

You can check what time date the timeinmillis (TimeStamp) refers to from this site.

http://currentmillis.com/

To get the correct time from unix time stamp just change your DateTime date = new DateTime(timestamp); into

    DateTime date = new DateTime(timestamp*1000);

Because unix time gives timpestamp in seconds and we need millis here.

Question:

I've recently switched to joda time LocalDate from Calendar to avoid timezone issues in my project (I don't need time zone there). At some point I need to get a Timestamp from a LocalDate:

  class DateTimeUtils{
   static Timestamp getDeadline(LocalDate localDate, int daysToAdd){
      localDate = localDate.plusDays(daysToAdd);
      System.out.println(localDate);//This prints 2017-06-02
      return new Timestamp(localDate.toDateTimeAtStartOfDay().getMillis());         
   }
  public static void main(String... args){
     LocalDate localDate= new LocalDate(2017,5,31);
     Timestamp timeStamp=getDeadline(localDate,2);
     System.out.println(timeStamp);//This prints 2017-06-01 23:00:00.0
  }
 }

For some reason that I can't figure out, after converting the localdate to timestamp, the result falls back to 23:00 of the previous day. Why is that?


Answer:

Time zone matters

to avoid timezone issues in my project

You cannot ignore time zone issues. Wishful dreaming. Be brave, grab the bull by the horns, and take on the challenge of learning to deal with time zones. Your programming work will be much easier.

In your call to toDateTimeAtStartOfDay, you chose to omit the argument for time zone, the DateTimeZone object. So, at runtime, the JVM’s current default time zone was silently implicitly applied.

Then you convert to a java.sql.Timestamp (apparently – you were not explicit about package) which is always in UTC.

You did not provide your runtime current default time zone, so I cannot be more exact in the details.

Using java.time

The Joda-Time project is now in maintenance mode, with its team advising migration to the java.time classes. Both projects were led by the same man, Stephen Colebourne, so the they share the same conceptual approach. Pretty easy to switch over.

To get today’s date, specify the time zone. For any given moment, the date varies around the globe by zone.

See how we pass the zone to atStartOfDay.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z );
LocalDate twoDaysLater = today.plusDays( 2 ) ;
ZonedDateTime zdt = twoDaysLater.atStartOfDay( z ) ;
Instant instant = zdt.toInstant();  // Instant is always in UTC by definition. 

With JDBC 4.2 and later, you can work directly with the java.time types. Call PreparedStatement.setObject and ResultSet.getObject.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Question:

I have the following code which gets offset from sql Timestamp object using the Joda Time Library.

public static long getOffset(Chronology chronology_, Timestamp timeStamp_)
  {
    long offset = 0;
    if (chronology_ != null)
      {
        offset = chronology_.getZone().getOffset(new DateTime(timeStamp_).getMillis());
      }
    return offset;
  }

How can achieve the same using Java 8 API. I am not sure if chronology is required any more.


Answer:

While the Joda-Time concept of a chronology and the java.time (JSR-310) concept of a chronology are similar, there is a difference that matters in your situation: The Joda-Time Chronology may (optionally) have a time zone. The java.time.chrono.Chronology cannot. So you need to provide the time zone to use for the operation in some other way than through a chronology.

Now we’re at it, I might suggest that you also provide the point in time in some other way than through a java.sql.Timestamp. So one option would be:

public static long getOffset(ZoneId zone, Instant when)
{
    long offset = 0;
    if (zone != null)
    {
        int offsetSeconds = zone.getRules()
                .getOffset(when)
                .getTotalSeconds();
        offset = TimeUnit.SECONDS.toMillis(offsetSeconds);
    }
    return offset;
}

If your caller has got an old-fashioned Timestamp from a legacy API that they cannot change, they should convert. So one way of calling the above method would be:

    long offsetMillis = getOffset(
            ZoneId.of("Africa/Khartoum"), theirTimesatmp.toInstant());
    System.out.println(offsetMillis);

An example output using a timestamp from around now:

7200000

The Timestamp class is poorly designed, a true hack on top of the already poorly designed java.util.Date class, so we should not use it. If we can’t avoid getting one, we should convert it to either Instant or LocalDateTime immediately and perform or further work from there.

A further nice improvement will be if your method returns the ZoneOffset object returned from getOffset() rather than a number that may leave a caller wondering whether it’s seconds, milliseconds or some other unit.

If you do insist on providing a convenience method that accepts a Timestamp, you may of course add a wrapper that is friendly to the past. For example:

/** @deprecated use {@link #getOffset(ZoneId, Instant)} instead */
public static long getOffset(ZoneId zone, Timestamp timeStampParam)
{
    return getOffset(zone, timeStampParam.toInstant());
}

Link: Converting from Joda-Time to java.time on Stephen Colebourne’s blog

Question:

I have a requirement to find the timestamp at the end of the month for a given time zone from a given timestamp.

The following code returns the start of the month timestamp in UTC

DateTime allInOneLine = new DateTime( DateTimeZone.forID( "Europe/Paris" ) ).plusMonths( 1 ).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();

returns:

2017-12-01T00:00:00.000Z

Any suggestions how I can get end month timestamp for a given timezone


Answer:

The following is a good starting point. I have passed in UTC , this can be made generic for any timezone

import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;
import static java.time.ZoneOffset.UTC;

public class TruncateToMonth {
    public static void main(String[] args) {
        ZonedDateTime now = ZonedDateTime.now(UTC);
        ZonedDateTime truncatedToMonth = now.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
        System.out.println(truncatedToMonth);
        System.out.println(truncatedToMonth.toInstant().getEpochSecond());
    }
}

Question:


Answer:

java.sql.Timestamp.toString() will print the timestamp in the current timezone, not UTC.

The value is correct, you're simply printing it wrong.

That internal value of Timestamp is in UTC, like all the other java.util.Date classes.

Question:

Here is the problem I am trying to solve: Read a string from database A, convert the string into a Date object, store the Date object into database B.

EX) Database A: Read in date string "2015-03-08 02:00:00" from database A, convert into a Date object, store back into database B.

The problem here occurs because 2:00 AM is the beginning of DST in U.S. Central time, so the Data object converts 2:00 AM straight into 3:00 AM, which means 3:00 AM gets stored into database B.

Is there any way to correct this? I am not opposed to using Joda Time if necessary.

I am trying to focus on the above date, 2015-03-08 02:00:00

This is the code I am using:

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String date = "2015-03-08 02:00:00.0";



    try 
    {
        d = sdf.parse(date);
        sdf.format(d);

        //Insert into database here
        // ---
        //
    } 
    catch (ParseException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Answer:

You have multiple issues intertwined.

You should not be reading strings from a database for date-time values, you should be reading date-time objects. There are many Questions on StackOverflow about reading/writing date-time values from/to databases, so no need to repeat here.

If you do have a string, such as "2015-03-08 02:00:00", notice the lack of any indicator of a time zone or offset. If you want to assume that string represents a time specific the US Central Time, then you must accept the fact that there is no such date-time as that because Daylight Saving Time (DST) defines that as 3 AM. At the stroke of 2 AM, the time labeling jumps to 2 AM. So there is no point in trying to get such a non-existent date-time.

Use Proper Time Zone Names

Big tip for date-time work: Avoid thinking about time zones as "Central Time" and the 3-4 letter codes like "CST". These are not standardized, nor are the unique (many duplicates), and further confuse the mess that is Daylight Saving Time. Use a proper time zone, in pattern of "continent/majorCityOrRegion".

Local Date-Time

Perhaps what you mean is what we call "local time" where the date-time is not specific to any one time zone. For example, "Christmas starts at midnight on December 25th 2015". That means a different moment in each particular time zone. Christmas dawns earlier in Paris, than Montréal, for example.

Joda-Time

Let's interpret that string as a LocalDateTime in Joda-Time. First, for convenience, we replace the SPACE with a "T" to take advantage of Joda-Time’s built-in parsers for ISO 8601 formats.

String input = "2015-03-08 02:00:00";
String inputStandardized = input.replace( " ", "T" );  // For convenience, convert input text to comply with ISO 8601 standard’s canonical format. Replace SPACE between date & time portions with "T".

Next we parse that standardized string.

LocalDateTime localDateTime = LocalDateTime.parse( inputStandardized );

Dump to console.

System.out.println( "inputStandardized: " + inputStandardized );
System.out.println( "localDateTime: " + localDateTime );

When run.

inputStandardized: 2015-03-08T02:00:00
localDateTime: 2015-03-08T02:00:00.000

This local date-time could be stored in a SQL database using the SQL type TIMESTAMP WITHOUT TIME ZONE. This type means no adjustments to UTC time zone are to be made in either getting (SELECT) or putting (INSERT / UPDATE) database values. See Postgres doc for more info on these SQL types.

Zoned Date-Time

If you meant to represent the specific moment in a specific time zone such as America/Chicago, when we need to assign that time zone. For this kind of time-zone-specific values, in your database you would use the data type TIMESTAMP WITH TIME ZONE. That type name is misleading -- it means with respect for time zone, as it adjusts incoming data to UTC. The data's original time zone is then lost.

Unfortunately, this is one of the few situations where Joda-Time lets us down. Rather than do an adjustment, Joda-Time refuses, throwing an exception. ☹

See for yourself… Let's add the following code to the example code above.

DateTimeZone zone = DateTimeZone.forID( "America/Chicago" );
DateTime dateTimeChicago = localDateTime.toDateTime( zone ); // If the input lacks an offset, then Joda-Time *assigns* the value the specified time zone. If the input has an offset, Joda-Time *adjusts* the value to the specified zone.

Dump to console.

System.out.println( "zone: " + zone );
System.out.println( "dateTime: " + dateTimeChicago );

When run.

Exception in thread "main" org.joda.time.IllegalInstantException: Illegal instant due to time zone offset transition (daylight savings time 'gap'): 2015-03-08T02:00:00.000 (America/Chicago
…

There appears to be no good generalized workaround, just hacks. Basically, if you expect a certain time zone, you make the adjustment yourself. See discussions like this, this, this, and the Joda-Time FAQ.

java.time

In Java 8 and later, we have the new built-in date-time framework in the java.time package (Tutorial). This framework was inspired by Joda-Time, and has some advantages over Joda-Time. One of those advantages is handling of this DST non-existent value problem.

String input = "2015-03-08 02:00:00";
String inputStandardized = input.replace( " ", "T" );  

LocalDateTime localDateTime = LocalDateTime.parse( inputStandardized );

Let's adjust that local date-time to assign a specific time zone. The java.time framework detects the non-existent date-time and automatically slides the time-of-day forward to respect the DST transition.

ZoneId zone = ZoneId.of( "America/Chicago" );
ZonedDateTime zdt = ZonedDateTime.of( localDateTime, zone );

Dump to console.

System.out.println("inputStandardized: " + inputStandardized );
System.out.println("localDateTime: " + localDateTime );
System.out.println("zone: " + zone );
System.out.println("zdt: " + zdt );

When run.

inputStandardized: 2015-03-08T02:00:00
localDateTime: 2015-03-08T02:00
zone: America/Chicago
zdt: 2015-03-08T03:00-05:00[America/Chicago]
SQL

As said above, you can search StackOveflow for much info on getting date-times in and out of databases.

Ideally, with java.time, you could directly feed either the LocalDateTime or ZonedDateTime to your JDBC driver. But most drivers have not yet be updated to handle the java.time types. Until your driver is updated, fall back on the java.sql.* classes. Convenient conversion methods can be found on both the new and old classes bundled with Java.

java.sql.Timestamp ts = java.sql.Timestamp.valueOf( localDateTime );

…or…

Instant instant = zdt.toInstant();
java.sql.Timestamp ts = java.sql.Timestamp.from( instant );

Question:

I have a timestamp in string, which is in UTC timezone, i want to read it as is in UTC timezone using DateTime in joda time library.

Example:

String utcTs = "2016-06-01T14:46:22.001Z";

when i try below stmt., DateTime is reading it and converting to servertimezone where ever the application is running!!

DateTime dtUtcTs = new DateTime(utcTs);

Is there a way i can force the DateTime to read the string timestamp as UTC ?

My application server is in CST, and when print the date with SOP stmt like below, i am observing CST time instead of UTC!!

System.out.println(dtUtcTs) ==> gives me date in server where the application is running!!

Thanks a lot!!

import org.joda.time.DateTime;

public class TestClass {

public static void main(String[] args) {

String utcTs = "2016-06-01T14:46:22.001Z";
DateTime dtUtcTs = new DateTime(utcTs);

System.out.println(dtUtcTs)

}
}

below is the output i see, my application server is in CST zone

2016-06-01T09:46:22.001-05:00

using joda time version 2.9.1


Answer:

You can just use the overload of the DateTime constructor that takes a DateTimeZone:

DateTime dtUtcTs = new DateTime(utcTs, DateTimeZone.UTC);

Another option is to use a DateTimeFormatter so you can specify exactly the format you expect, and what time zone you want.

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        String text = "2016-06-01T14:46:22.001Z";
        DateTime dt = ISODateTimeFormat.dateTime()
            .withZone(DateTimeZone.UTC)
            .parseDateTime(text);
        System.out.println(dt);
    }
}

Question:

I am experimenting some stange issues while trying to convert an object of type java.sql.Timestamp into an object of time org.joda.time.DateTime. In detail, the Timezone is not set correctly.

Here is my code (scala language):

val receptionDate = 
  new DateTime(tuple("RECEPTION_TIMESTAMP").asInstanceOf[Timestamp].getTime(), 
               DateTimeZone.UTC)

The Timestamp object is read directly from a database table (HBase) and the value showed by SQuirreL client is the following:

2015-07-30 00:00:00.0

Instead, the DateTime object created has the value 2015-07-29 22:00:00.0. Clearly during the creation of the DateTime object it is not used the information of the timezone DateTimeZone.UTC, that I am passing to the constructor.

What am I doing wrong? Where is the error?


Answer:

This issue is caused by you are using your local Timezone(UTC-2) to store date without specifying UTC Timezone, but When you retrieve your date from Hbase with setting UTC Timezone. so they are equal time, but are not same Timezone.

Question:

I have written the following function in Scala which works:

import java.text.SimpleDateFormat
import java.util.{Calendar, Date}
import java.util.{TimeZone, Date}


val curr_timeFmt = "YYYY_MM_dd_HH_mm_ss"

def curr_time(): String = {
    val date = new Date
    val currTS = new SimpleDateFormat(curr_timeFmt)
    currTS.setTimeZone(TimeZone.getTimeZone("EST"));
    currTS.format(date)
  }

I would like to store the return value from this function as a timestamp in a PG columnn of type timestamp.

Furthermore, while researching online, I heard that the the Java Calendar and Date classes are not thread safe and mutable. Is this true, if so how can I use the new joda time in Java 8?

Any help would be greatly appreciated, as Ive been looking online for a while and tried a few things and nothing seemed to work.

Thx


Answer:

To get the current time in US Eastern time zone, in that format, using Java 8 Time API:

val fmt = DateTimeFormatter.ofPattern("uuuu_MM_dd_HH_mm_ss")
val time = LocalDateTime.now(ZoneId.of("America/New_York")).format(fmt)

Printing value of time shows e.g.

2019_03_18_21_32_22

Question:

I have a timestamp datatype field called created in a derby database.

I'm using JAVA with the following insert call to insert the created field in the database:

new Timestamp(new DateTime().getMillis());

Two questions:

  1. Not sure if this is possible but our requirements are that the created field is stored in this format:

    YYYYMMDDHHMMSSFF

  2. We need to somehow retrieve the field (from step 1) from the database to a joda DateTime field in this format: YYYYMMDDHHMMSSFF

how do we go about doing #1 and #2 above in Java?

I have tried the below code in Java to retrieve the data right now but that is not how is needed:

Timestamp ts= (Timestamp)row.get("created");

DateTime storedatetime = new DateTime(ts);

Thanks for your help.


Answer:

... our requirements are that the created field is stored in this format: YYYYMMDDHHMMSSFF"

A timestamp is a value that represents an instant in time. It is defined by its resolution (i.e. what's the smallest increment of time it can represent) but you should not care at all about how it is physically stored in a database.

A timestamp by itself does not have a format, but can be rendered for display in many different formats.

If the requirement really means "the field must represent times with at least two digits precision" then a standard database timestamp column will do just fine.

If the requirement is really "the timestamp must be displayed in the format..." then again a database timestamp will suffice, and you must ensure that whenever you output the value to an external medium (i.e. a report or web page) that you format it correctly.