package com.s1;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;//1、巴黎时间比北京时间晚7个小时,
//纽约时间比北京时间晚12个小时,
//试编写一程序,根据输入的北京时间输出相应的巴黎和纽约时间。[选做题]
public class Demo4 { public static void main(String[] args) throws ParseException {
System.out.println("请输入北京时间");
Scanner sc = new Scanner(System.in);
String s = sc.next();
SimpleDateFormat si = new SimpleDateFormat("yyyy-MM-dd-HH"); Date parse = si.parse(s);
Calendar c = Calendar.getInstance();
// 设置时间
c.setTime(parse);
// 修改成巴黎的时间
c.add(c.HOUR_OF_DAY, -7);
// 巴黎时间
double y1 = c.get(c.YEAR);
double m1 = c.get(c.MONTH);
double d1 = c.get(c.DAY_OF_MONTH);
double h1 = c.get(c.HOUR_OF_DAY);// 修改成纽约的时间
c.add(c.HOUR_OF_DAY, -5);
// 纽约时间
double y2 = c.get(c.YEAR);
double m2 = c.get(c.MONTH);
double d2 = c.get(c.DAY_OF_MONTH);
double h2 = c.get(c.HOUR_OF_DAY);// 输出巴黎时间
System.out.println("巴黎时间是" + y1 + "-" + m1 + "-" + d1 + "-" + h1);
// 输出纽约时间
System.out.println("纽约时间是" + y2 + "-" + m2 + "-" + d2 + "-" + h2); }
}

解决方案 »

  1.   

    最好用系统定义的时区,纽约与北京差13小时。public class DateTimeDemo {
        static final ZoneId ZONE_SHANGHAI = ZoneId.of("Asia/Shanghai");
        static final ZoneId ZONE_PARIS = ZoneId.of("Europe/Paris");
        static final ZoneId ZONE_NEWYORK = ZoneId.of("America/New_York");    private final DateTimeFormatter formatter;

        public DateTimeDemo(String datetimePattern) {
            formatter = DateTimeFormatter.ofPattern(datetimePattern, Locale.CHINA);
        }

        public static void main(String[] args) {
            DateTimeDemo demo = new DateTimeDemo("yyyy-MM-d HH:mm:ss");
            Scanner sc = new Scanner(System.in);
            String text;
            ZonedDateTime time;
            while (true) {
                System.out.println("请输入北京时间,或exit退出:");
                text = sc.nextLine();
                if ("exit".equalsIgnoreCase(text)) {
                    break;
                }
                try {
                    time = demo.parseBeijingTime(text);
                    demo.printTime(time);
                    demo.printTime(time.withZoneSameInstant(ZONE_PARIS));
                    demo.printTime(time.withZoneSameInstant(ZONE_NEWYORK));
                } catch (DateTimeParseException e) {
                    System.out.println("时间格式错误!");
                }
            }

            sc.close();

        }    public ZonedDateTime parseBeijingTime(String text) {
            LocalDateTime localTime = LocalDateTime.parse(text, formatter);
            return localTime.atZone(ZONE_SHANGHAI);
        }

        public void printTime(ZonedDateTime time) {
            System.out.println(time.getZone() + ": " + time.format(formatter));
        }
    }
      

  2.   

    代码中
    // 修改成纽约的时间
    c.add(c.HOUR_OF_DAY, -5);
    这里不是应该-12吗? 纽约时间比北京时间晚12个小时