-2

I have a line of C# code that I am trying to replicate in Java. The code looks as follows.

n.InnerText = DateTime.Parse(n.InnerText).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");

The intent is to replace the DateTime already in the xml context with one representing universal time.

I have attempted to use

node.setTextContent = Date.parse(node.getTextContent())

but I am unable to continue due to the Date.parse() being deprecated. I read through the note in Eclipse and tried DateFormat as suggested but DateFormat does not have a parse method.

Can someone suggest a solution to my problem that does not use any third party libraries?

Veer
  • 1,575
  • 3
  • 16
  • 40
JME
  • 2,293
  • 9
  • 36
  • 56
  • Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s). – ageoff Jun 03 '13 at 13:50
  • @Johnathon Ender , Check http://stackoverflow.com/a/9886992/1160207 and reference http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html – Never Quit Jun 03 '13 at 13:52

5 Answers5

7

You can use:

DateFormat format = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ssZ");
Date date = format.parse(myString);

Be sure to check the locale if it's appropriate, and to check that the fields are the same (as I don't know what you intended to parse, I just copied them).

(For example "T" does not exist.)

Djon
  • 2,230
  • 14
  • 19
3
  Date d = new Date();
  (java.text) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
  sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
  String formatted = sdf.format(d);
Bob Flannigon
  • 1,204
  • 9
  • 8
2

The other answers are outdated, using old legacy classes.

java.time

The java.time framework built into Java 8 and later supplants the troublesome old date-time classes.

ISO 8601

Your input string happens to be in standard ISO 8601 format.

The java.time classes use ISO 8601 formats by default when parsing/generating String representations of date-time values. So no need to specify a formatting pattern.

An Instant represents a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.parse( "2016-04-29T22:04:07Z" );
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

You mean like this one:

import java.util.Date;
import java.text.SimpleDateFormat;

public class DateFormat{
  public static void main(String[] args){

    Date date=new Date();
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

    String yourDate=sdf.format(date);
    System.out.println(yourDate);

  }
}
A-SM
  • 882
  • 2
  • 6
  • 18
0
package com.pnac;

import org.joda.time.DateTime;

public class TestDateTime {
    public static void main(String[] args) {
        DateTime dateTime = new DateTime();

        System.out.println("@@@@@@@@@@ " + dateTime.minusHours(10).toString("yyyy-MM-dd HH:mm:ss"));
    }
}
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61