My java timestamp has the following format:
YYYY-MM-DD hh:mm:ss.ms
2016-01-08 15:16:44.554
I got it using the following method:
private String getCurrentTimeStamp() {
Date date= new java.util.Date();
return((new Timestamp(date.getTime())).toString());
}
Is there a standardized xml date and Time format for timestamp? The xs: dateTime has the following format: "YYYY-MM-DDThh: mm: SS" And it is not taking into consideration milliseconds.
XML itself does not define any timestamp formats.
XML Schema Part 2: Datatypes Second Edition incorporates ISO 8601 formats by reference. The dateTime format allows but does not require a decimal point followed by arbitrary fractions of a second. For example, 2016-01-08T15:16:44.554
In XML Schema (XSD), all formats of dates and times are well defined.
The java.time framework built into Java 8 and later supports these formats. See Tutorial.
Here are some examples:
// Dates in XML: YYYY-MM-DD
DateTimeFormatter.ISO_LOCAL_DATE.parse("2002-09-24");
// Dates with TimeZone in XML: YYYY-MM-DDZ
DateTimeFormatter.ISO_DATE.parse("2002-09-24Z");
// Dates with TimeZone in XML: YYYY-MM-DD-06:00 or YYYY-MM-DD+06:00
DateTimeFormatter.ISO_DATE.parse("2002-09-24-06:00");
// Times in XML: hh:mm:ss
DateTimeFormatter.ISO_TIME.parse("09:00:00");
DateTimeFormatter.ISO_TIME.parse("09:00:00.5");
// DateTimes in XML: YYYY-MM-DDThh:mm:ss (with an optional TimeZone)
DateTimeFormatter.ISO_DATE_TIME.parse("2002-05-30T09:00:00");
DateTimeFormatter.ISO_DATE_TIME.parse("2002-05-30T09:30:10.5");
DateTimeFormatter.ISO_DATE_TIME.parse("2002-05-30T09:00:00Z");
DateTimeFormatter.ISO_DATE_TIME.parse("2002-05-30T09:30:10.5-06:00");
Durations and Periods however are not perfectly compatible, because they are split in Durations and Periods in Java. Here are however some examples:
Period.parse("P5Y");
Period.parse("P5Y2M10D");
Duration.parse("PT15H");
Duration.parse("-P10D");
If you can't change the schema, you have to change your function
private String getCurrentTimeStamp() {
Date date = new java.util.Date();
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(date);
}
Maybe you mean the standart ISO for Date.
On this thread
Convert Java Date...
See also:
What is Jaxb and why would i use it
There seems to be a format as part of XSD 1.1:
The type xsd:dateTimeStamp represents a specific date
and time in the format CCYY-MM-DDThh:mm:ss.sss.
http://www.datypic.com/sc/xsd11/t-xsd_dateTimeStamp.html
Related
I want to convert date and time to user requested timezone. date and time is in GMT format. i tried got the solution but the final string contains GMT String in resultant date like (2019-09-18T01:44:35GMT-04:00). i don't want GMT String in the resultant output.
public static String cnvtGMTtoUserReqTZ(String date, String format, String timeZone) {
// null check
if (date == null)
return null;
// create SimpleDateFormat object with input format
SimpleDateFormat sdf = new SimpleDateFormat(format);
// set timezone to SimpleDateFormat
sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
try {
// converting date from String type to Date type
Date _date = sdf.parse(date);
// return Date in required format with timezone as String
return sdf.format(_date);
} catch (ParseException e) {
//log.info("Exception in cnvtGMTtoUserReqTime ::: " + e);
}
return null;
}
Actual Output : 2019-09-18T01:44:35GMT-04:00
Expected Output: 2019-09-18T01:44:35-04:00
Proces datetime objects, not strings
Your question is put in the wrong way, which is most likely due to a design flaw in your program. You should not handle date and time as strings in your program. Always keep date and time in proper datetime objects such as Instant, OffsetDateTime and ZonedDateTime. The mentioned classes are from java.time, the modern Java date and time API, which is the best we have for keeping and processing datetime data.
So your question may for example become: How to convert a moment in time to user requested timezone? A moment in time is represented by an Instant object. And the answer to the question is:
ZoneId userRequestedTimeZone = ZoneId.of("America/New_York");
Instant moment = Instant.parse("2019-09-18T05:44:35Z");
ZonedDateTime userDateTime = moment.atZone(userRequestedTimeZone);
System.out.println(userDateTime);
Please substitute your user’s desired time zone where I put America/New_York. Always give time zone in this format (region/city). Output from the snippet as it stands is:
2019-09-18T01:44:35-04:00[America/New_York]
Assuming that you don’t want the [America/New_York] part of the output, format the datetime to the string that you want:
String dateTimeWithNoZoneId = userDateTime.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(dateTimeWithNoZoneId);
2019-09-18T01:44:35-04:00
The latter output is in ISO 8601 format. This format is good for serialization, that is, if you need to convert the datetime to a machine readable textual format, for example for persistence or exchange with other systems. While also human readable, it’s not what your user prefers to see. And as I said, it’s certainly not what you should be handling and processing inside your program.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
Use these formats:
fromFormat = "yyyy-mm-dd'T'HH:mm:sszXXX"
toFormat = "yyyy-mm-dd'T'HH:mm:ssXXX"
For more details see examples listed here
My app is using JodaTime to manage date parsing and formatting.
I have this timestamp: 2018-07-24T15:30:00-07:00.
How can display it as 3:30pm, regardless of the user's whereabouts?
Following code will print "3:30pm":
DateTimeFormatter iso = ISODateTimeFormat.dateTimeParser().withOffsetParsed();
DateTime tsp = iso.parseDateTime("2018-07-24T15:30:00-07:00");
DateTimeFormatter out = DateTimeFormat.forPattern("h:mma").withLocale(Locale.ENGLISH);
System.out.println(tsp); // 2018-07-24T15:30:00.000-07:00
System.out.println(out.print(tsp).toLowerCase()); // 3:30pm
The main problem is just that the parser does not retain the parsed offset of -7:00 but shifts it to your system timezone unless you also call withOffsetParsed().
I want to convert from string to date using Java 8.
I can easily convert using SimpleDateFormat and yyyy-MM-dd format
String startDate2="2017-03-24";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(new java.sql.Date(sdf1.parse(startDate2).getTime()));
output:
2017-03-24
String startDate2="2017-03-24";
SimpleDateFormat sdf1 = new SimpleDateFormat("uuuu-MM-dd");
System.out.println(new java.sql.Date(sdf1.parse(startDate2).getTime()));
But when I use 'uuuu-MM-dd' instead of 'yyyy-MM-dd'
output :
1970-03-24(wrong)
now in Java 8:
String startDate1="2017-03-23";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd");
But I don't know how I can get the date which would be sql date type same as above correct output.
java.sql.Date has a static valueOf method that takes a Java 8 LocalDate so you can do:
String startDate1 = "2017-03-23";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd");
LocalDate date = LocalDate.parse(startDate1, formatter);
java.sql.Date sqlDate = java.sql.Date.valueOf(date);
As far as I can see, you have a text in yyyy-MM-dd format and you want it in uuuu-MM-dd format. So you need two formats:
String startDate2="2017-03-24";
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat targetFormat = new SimpleDateFormat("uuuu-MM-dd");
java.sql.Date date = new java.sql.Date(sourceFormat.parse(startDate2).getTime());
String formattedAsDayOfWeek = targetFormat.format(date);
System.out.println(formattedAsDayOfWeek);
Bottom line is that Date contains a millisecond value. java.sql.Date.toString() uses the yyyy-MM-dd format regardless how you parsed it. java.util.sql.Date uses another format: EEE MMM dd hh:mm:ss zzz yyyy with English Locale.
You can do other formatting with DateFormat -s.
I presume you need the uuuu-MM-dd format for inserting data to the database. What does that logic look like?
You don’t want a java.sql.Date. You want a LocalDate. Your SQL database wants one too.
String startDate2 = "2017-03-24";
LocalDate date = LocalDate.parse(startDate2);
System.out.println(date);
Output is:
2017-03-24
I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time including LocalDate parse this format as their default, that is, without any explicit formatter.
You also note that we don’t need any explicit formatter for formatting back into uuuu-MM-dd format for the output. The toString method implicitly called from System..out.println() produces ISO 8601 format back.
Assuming that you are using a JDBC 4.2 compliant driver (I think we all are now), I am taking the way to pass it on to your SQL database from this question: Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2:
myPreparedStatement.setObject ( 1 , date ); // Automatic detection and conversion of data type.
Refer to the linked question for much more detail.
The java.sql.Date class is poorly designed, a true hack on top of the already poorly designed java.util.Date class. Both classes are long outdated. Don’t use any of them anymore.
One more link: Wikipedia article: ISO 8601
After a week of going through so many examples, and moving from Java Date,
to Calendar, to Joda. I have decided to seek help from other sources.
The problem:
Our table has two fields Date (Timestamp), and TZ (String). The idea is to store
the user's UTC in timestamp, and timezone, well, you get the idea. So basically
we think in UTC, and present the user with the time converted to their
timezone on the front end (ie, using the value store in table.TZ)
Another requirement is to use the proper Object (Date, DateTime whatever).
And not pass a String representation of the date around. The best would
be a valid Long that will be correctly translated by MySQL, without having
to use the FROM_UNIXTIME mysql function in our query.
Code we are using:
public DateTime convertTimezone(LocalDateTime date, DateTimeZone srcTZ, DateTimeZone dstTZ, Locale l) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withLocale(l);
DateTime srcDateTime = date.toDateTime(srcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(dstTZ);
System.out.println(formatter.print(dstDateTime));
System.out.println(formatter.parseDateTime(dstDateTime.toString()));
return formatter.parseDateTime(formatter.print(dstDateTime));
}
The String output is exactly what we need (ie UTC time, 2013-08-23 18:19:12),
but the formatter.parseDateTime(dstDateTime.toString() is crashing with the following
error. Probably because of the UTC timezone independent info, and milleseconds?:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2013-08- 23T18:19:12.515Z" is malformed at "T18:19:12.515Z"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:873)
at com.example.business.rate.RateDeck.convertTimezone(RateDeck.java:75)
at com.example.business.rate.RateDeck.WriteData(RateDeck.java:143)
at com.example.business.rate.RateDeck.main(RateDeck.java:64)
Search engine enriched question:
How to format UTC for Joda DateTime.
PS My first SO post, and it feels nice? :)
Thanks in Advance,
The new fixed version:
public Timestamp convertTimezone(LocalDateTime date, DateTimeZone srcTZ, DateTimeZone dstTZ, Locale l) {
DateTime srcDateTime = date.toDateTime(srcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(dstTZ);
return new Timestamp(dstDateTime.getMillis());
}
Nick.
It's simply crashing because the format of the parsed string doesn't match with the format of the formatter.
The formatter parses using the format yyyy-MM-dd HH:mm:ss, and the toString() method of DateTime formats the date it using (as documented) the ISO8601 format (yyyy-MM-ddTHH:mm:ss.SSSZZ).
Is there a date formatting tool for Atom Dates.
According to this link:
https://www.rfc-editor.org/rfc/rfc4287
Such date values happen to be compatible with the following
specifications: [ISO.8601.1988], [W3C.NOTE-datetime-19980827], and
[W3C.REC-xmlschema-2-20041028].
Example Date constructs:
<updated>2003-12-13T18:30:02Z</updated>
<updated>2003-12-13T18:30:02.25Z</updated>
<updated>2003-12-13T18:30:02+01:00</updated>
<updated>2003-12-13T18:30:02.25+01:00</updated>
I tried to use Joda ISODateTimeFormat.dateTime(); but it seems it doesn't handle the parsing when there is no milliseconds (2003-12-13T18:30:02Z for exemple).
What is the simplest way to parse all these date formats?
This is ISO 8601 format, the standard format used in for example XML. Joda Time supports this format very well, you can just pass these strings to the constructor of DateTime:
DateTime timestamp = new DateTime("2003-12-13T18:30:02Z");
Works without any problems, also if there are no milliseconds in the string.
It seems to be xml dateTime. Then the best choice is javax.xml.datatype.XMLGregorianCalendar.
DatatypeFactory f = DatatypeFactory.newInstance();
XMLGregorianCalendar xgc = f.newXMLGregorianCalendar("2003-12-13T18:30:02.25Z");
System.out.println(xgc);
System.out.println(xgc.toGregorianCalendar().getTime());
output
2003-12-13T18:30:02.25Z
Sat Dec 13 20:30:02 EET 2003
See more in API
DateUtils from Apache Commons / Lang has a parseDate method that supports multiple patterns. That may work for you. (The patterns must be formatted according to the SimpleDateFormat syntax)