36

Joda Timeで実際の日付と時刻を適切に取得するには? 正確には、私の国での時間を意味します。公式ページといくつかのチュートリアルを読みました。ロケールとタイムゾーンについては多くのことが書かれていますが、非常にわかりにくいことがわかりました。単純に取得する方法の例は見つかりませんでした。

私は2つのことのためにそれを必要とします:

  1. ディスカッションの投稿の最新情報を取得するには、
  2. 生年月日と「比較」して年齢を計算する現在の時刻を取得します。

UTC+1 (プラハ - チェコ共和国) を使用している場合、現在の時刻を設定するにはどうすればよいですか?

4

2 に答える 2

54

Joda Time の疑似コードを次に示します。これは役に立つ可能性があります。

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

public class JodaTimeExample {

    public static void main(String[] sm) {
        DateTimeFormatter dateFormat = DateTimeFormat
                .forPattern("G,C,Y,x,w,e,E,Y,D,M,d,a,K,h,H,k,m,s,S,z,Z");

        String dob = "2002-01-15";
        LocalTime localTime = new LocalTime();
        LocalDate localDate = new LocalDate();
        DateTime dateTime = new DateTime();
        LocalDateTime localDateTime = new LocalDateTime();
        DateTimeZone dateTimeZone = DateTimeZone.getDefault();

        System.out
                .println("dateFormatr : " + dateFormat.print(localDateTime));
        System.out.println("LocalTime : " + localTime.toString());
        System.out.println("localDate : " + localDate.toString());
        System.out.println("dateTime : " + dateTime.toString());
        System.out.println("localDateTime : " + localDateTime.toString());
        System.out.println("DateTimeZone : " + dateTimeZone.toString());
        System.out.println("Year Difference : "
                + Years.yearsBetween(DateTime.parse(dob), dateTime).getYears());
        System.out.println("Month Difference : "
                + Months.monthsBetween(DateTime.parse(dob), dateTime)
                        .getMonths());
    }
}

DateTimeFormat フォーマッタへのリンク

Joda 時間 API

これがお役に立てば幸いです。ご不明な点がございましたら、お知らせください。

PS: 出力を提供してくれた Sumit Arora に感謝します。

dateFormatr : AD,20,2016,2016,26,2,Tue,2016,180,6,28,PM,8,8,20,20,25,20,2,‌​, 
LocalTime : 20:25:17.308 
localDate : 2016-06-28 
dateTime : 2016-06-28T20:25:18.872+05:30 
localDateTime : 2016-06-28T20:25:20.260 
DateTimeZone : Asia/Kolkata 
Year Difference : 14 
Month Difference : 173
于 2013-01-15T17:34:24.733 に答える
7
LocalTime localTime = new LocalTime();
LocalDate localDate = new LocalDate();
DateTime dateTime = new DateTime();
LocalDateTime localDateTime = new LocalDateTime();  

このコンストラクターのいずれかがタイムゾーンで日付を作成します。ここで、タイムゾーンはタイムゾーンを意味しますDateTimeZone.getDefault();

現在の日付と生年月日を比較します。データベースに汚れの日付をどのように保存しますか?
UTCタイムゾーンの場合、UTC TZのdateTimeと比較できます

Years.yearsBetween(dateOfBirth, new DateTime(DateTimeZone.UTC));   

サーバーTZがある場合は、行う必要があります

Years.yearsBetween(dateOfBirth, new DateTime());  

サーバーTZがある場合は、行う必要があります

Years.yearsBetween(dateOfBirth, new DateTime(DateTimeZone.forID("ClientTZ")));  
于 2013-01-15T08:25:30.293 に答える