Getting UTC time with Calendar and Date

This question already has an answer here:

  • Calendar.getInstance(TimeZone.getTimeZone(“UTC”)) is not returning UTC time 5 answers

  • This question has already been answered here

    The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.

    You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.

    TimeZone timeZone = TimeZone.getTimeZone("UTC");
    Calendar calendar = Calendar.getInstance(timeZone);
    SimpleDateFormat simpleDateFormat = 
       new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
    simpleDateFormat.setTimeZone(timeZone);
    
    System.out.println("Time zone: " + timeZone.getID());
    System.out.println("default time zone: " + TimeZone.getDefault().getID());
    System.out.println();
    
    System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
    System.out.println("Default: " + calendar.getTime());
    

    Edit To convert cal to date

          Calendar cal = Calendar.getInstance();
          int year = cal.get(Calendar.YEAR);
          int month = cal.get(Calendar.MONTH);
          int day = cal.get(Calendar.DATE);
          System.out.println(year);
          Date date = new Date(year - 1900, month, day);  // is same as date = new Date();
    

    Just build the Date object using the Cal values. Please let me know if that helps.


    尝试使用日期格式化程序并将时区设置为UTC。

    dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); 
    
    链接地址: http://www.djcxy.com/p/18700.html

    上一篇: 如何使用SimpleDateFormat.parse()将Calendar.toString()转换为日期?

    下一篇: 使用日历和日期获取UTC时间