【问题标题】:Java time manipulation - subtracting 2 stringsJava时间操作 - 减去2个字符串
【发布时间】:2014-05-30 02:09:51
【问题描述】:

我正在使用 xpath 从 XML 文件中提取 2 个时间值(作为字符串),这些值(例如)如下:

00:07

08:00

00:07 等于 7 分钟

08:00 表示上午 8 点,没有关联或不需要日期(在其他地方处理)

这些值中的每一个都会在我阅读的每个 XML 文件中发生变化。我正在尝试做的事情如下:

  1. 我需要从早上 8 点减去或添加(视情况而定)7 分钟,并在我最终可以输出到 CSV 的字符串中给我一个 hh:mm 时间(例如:07:53 或 08:07)
  2. 接下来我需要生成 2 个额外的字符串,分别是之前 1 分钟和之后 1 分钟(例如:07:52 和 07:54 或 08:06 和 08:08),这些字符串也需要输出到 CSV

我已经尝试了所有方法,我可以想到与时间解释和操作相关的时间,以将分钟减去/添加到时间,然后从那里减去 +/- 1 分钟,但是作为一个完整的新手,我完全被困住了,尽管尽可能多地阅读和测试。过去 2 天是第一次与 Joda Time 一起工作,但我一定错过了一些基本的东西,因为我也无法得到想要的结果。

问题是 - 我怎样才能做到这一点?

一些示例代码让我从 XML 中读取并打印时间

 FileInputStream file = null;
    try {
        file = new FileInputStream(new File("Output/XmlConfig.xml"));
    } catch (FileNotFoundException ex) {
        Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
    }
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
    try {
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
    }
        Document xmlDocument = null;
    try {
        xmlDocument = builder.parse(file);
    } catch (SAXException ex) {
        Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
    }
        XPath xPath = XPathFactory.newInstance().newXPath();

        //get In Early rule from XML
        String exceptionInEarlyXML = "Root/Response/WSAExceptionRule/@InEarly";
        NodeList nodeListInEarly = null;
    try {
        nodeListInEarly = (NodeList) xPath.compile(exceptionInEarlyXML).evaluate(xmlDocument, XPathConstants.NODESET);
    } catch (XPathExpressionException ex) {
        Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
    }
        String exceptionInEarly = (nodeListInEarly.item(1).getFirstChild().getNodeValue());
       String InEarly = exceptionInEarly;
        SimpleDateFormat format = new SimpleDateFormat("hh:mm");
       Date d2 = null;

    try {
        d2 = format.parse(InEarly);
    } catch (ParseException ex) {
        Logger.getLogger(KATT.class.getName()).log(Level.SEVERE, null, ex);
    }

        DateTime dt2 = new DateTime(d2);

        System.out.println(dt2);

这给了我 1970-01-01T00:07:00.000+10:00 的输出

我已经尝试了很多代码排列,因为它不可编译,所以我要删除并重新从头开始,而且我还没有足够的经验来解决这个问题。

【问题讨论】:

  • 如果您有"tried everything""spent the last 2 days...",请向我们展示您的努力成果。
  • 1970-01-01T00:07:00.000+10:00 有什么问题?
  • 我不知道如何从这个值中减去 x 分钟(00:07 基于我从 xml 中提取的另一个字符串)并给我一个 07:53 的输出。

标签: java xml string swing jodatime


【解决方案1】:

一旦你有了解析时间的 Date 对象,就可以使用 getTime() 获取以毫秒为单位的时间并将其保存到一个 long 变量中。然后解析偏移时间格式并使用 NumberFormat 来获取要偏移的分钟数。根据需要添加或减去。获取结果并创建一个新的 Date(millis) 然后将您的格式应用到它。

这是一个工作示例:

    String sTime = "08:00";
    String sOffset ="00:07";
    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm");
    Date dtTime = null;
    try {
        dtTime = dateFormat.parse(sTime);
    } catch (ParseException e) {
        // handle exception
        return;
    }

    String[] offsetHrsMins = null;
    NumberFormat numberFormat = NumberFormat.getNumberInstance();
    long offsetMillis = 0;
    try {
        offsetHrsMins = sOffset.split(":");
        long offsetHrs = (Long) numberFormat.parse(offsetHrsMins[0]);
        long offsetMins = (Long) numberFormat.parse(offsetHrsMins[1]);
        offsetMillis = 1000 * 60 * ((offsetHrs * 60) + offsetMins);
    } catch (ParseException e) {
        // handle exception
        return;
    }

    long lTime = dtTime.getTime();

    System.out.println("Adding minutes: " + dateFormat.format(new Date(lTime + offsetMillis)));
    System.out.println("Subtracting minutes: " + dateFormat.format(new Date(lTime - offsetMillis)));

输出:

Adding minutes: 08:07
Subtracting minutes: 07:53

【讨论】:

  • 谢谢 - 这个解决方案似乎很适合我的要求!非常感谢。
【解决方案2】:

首先,您需要使用 SimpleDateFormat 将日期字符串解析为 Java.util.Date 对象。

第二,得到Date Object后,可以很方便的加减一些时间,得到另一个Date Object。

最后,您可以使用另一个 SimpleDateFormat 对象将您在第二步中获得的日期对象格式化为字符串。

SimpleDateFormat 在处理日期字符串时非常有用。你可以参考JDK中的Javadoc或者谷歌搜索一些例子。

【讨论】:

    【解决方案3】:

    尝试将字符串传递给一个方法,就像你要减去的一样

    然后将它们转换为整数

    然后有一个 if 语句,如果减法量大于 minets int 然后它从 hours int 中减去 1 并将 new minets int 设置为 60 减去减法 int

    然后将它们转换回字符串 这是将其转换回字符串的示例代码

        public class Main {
        static String hours="8";
    static String minets="7";
    static String minus="17";
    public static void main(String[] args) {
    Main m = new Main();
    
    m.timechange(hours,minets,minus);
    }
    void timechange(String hour, String minuet, String subtract){
        int h = Integer.parseInt(hour);
        int m = Integer.parseInt(minuet);
        int s = Integer.parseInt(subtract);
          if(s>m){
        h-=1;
        m=60-s;
          }
          else{
        m-=s;
          }
          if ((m>9)&&(h>9)) {
                System.out.println(h+":"+m);
            } else {if ((m<10)&&(h<10)) {
                System.out.println("0"+h+":0"+m);
            }else {if ((m<10)&&(h>9)) {
                System.out.println(h+":0"+m);
            }else {if ((m>9)&&(h<10)) {
                System.out.println("0"+h+":"+m);
            }
    
            }
    
            }
          }
    }}
    

    我不确定你是否想要返回 String。 希望能回答你的问题 如果发生这种情况,当矿工超过 60 时也可以这样做。

    【讨论】:

      【解决方案4】:

      这是一个真正的 Joda-Time 答案,因为 OP 想要 Joda-Time(我也认为该库优于 java.util.Datejava.text.SimpleDateFormat 等):

      Joda-Time 具有多种不同时间类型的巨大优势。处理普通时间的正确类型是LocalTime。它还定义了一种添加分钟的方法。

      你的任务:

      1. 我需要从早上 8 点减去或添加(视情况而定)7 分钟,并在我最终可以输出的字符串中给我一个 hh:mm 时间(例如:07:53 或 08:07)转为 CSV

      2. 接下来我需要生成 2 个额外的字符串,分别是之前 1 分钟和之后 1 分钟(例如:07:52 和 07:54 或 08:06 和 08:08),这些字符串也需要输出到 CSV

      解决方法(只针对第一部分,其他部分非常相似):

      LocalTime time = new LocalTime(8, 0); // corresponds to 08:00
      LocalTime laterBy8Minutes = time.plusMinutes(7);
      LocalTime earlierBy8Minutes = time.minusMinutes(7);
      String sLaterBy8Minutes = laterBy8Minutes.toString("HH:mm"); // 08:07
      String sEarlierBy8Minutes = earlierBy8Minutes.toString("HH:mm"); // 07:53
      

      附加说明:如果您从java.util.Date 等其他类型开始并希望将其转换为LocalTime,那么您可以使用构造函数

      new LocalTime(jdkDate, DateTimeZone.forID("Europe/Moscow"))  // example
      

      或默认时区:

      new LocalTime(jdkDate)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-17
        • 2018-10-05
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多