Get locale specific date/time format in Java - java

I have use case in java where we want get the locale specific date. I am using DateFormat.getDateInstance
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM,
Locale.forLanguageTag(locale)));
This translates the dates but ja-JP this translates the date "17 January 2019" to "2019/01/17" but I need something like "2019年1月17日". For all other locales this correctly translates the date.
Please let know if there is other method to get this.

This worked for me:
public static void main(String[] args) throws IOException {
final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.JAPAN);
Date today = new Date();
System.out.printf("%s%n", dateFormat.format(today));
}
and MEDIUM acted exactly how you said
UPD: or using newer ZonedDataTime as Michael Gantman suggested:
public static void main(String[] args) throws IOException {
ZonedDateTime zoned = ZonedDateTime.now();
DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(Locale.JAPAN);
System.out.println(zoned.format(pattern));
}

Just to mention: SimpleDateFormat is an old way to format dates which BTW is not thread safe. Since Java 8 there are new packages called java.time and java.time.format and you should use those to work with dates. For your purposes you should use class ZonedDateTime Do something like this:
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("..."));
to find out correct zone id for Japan use
ZoneId.getAvailableZoneIds()
Later on to format your Date correctly use class DateTimeFormatter

The trick is to use java.time.format.FormatStyle.LONG:
jshell> java.time.format.DateTimeFormatter.ofLocalizedDate(java.time.format.FormatStyle.LONG).withLocale(java.util.Locale.JAPAN)
$13 ==> Localized(LONG,)
jshell> java.time.LocalDate.now().format($13)
$14 ==> "2019年1月17日"

Related

how to convert string date in UTC format using joda date time

public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
try {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime date = formatter.parseDateTime(dateTime).withZoneRetainFields(DateTimeZone.UTC);
return date.toString("h:mm aa");
} catch (Exception e) {
return null;
}
}
main(){
print(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"))
}
I am trying to convert given date-time in UTC format using joda date time it's giving wrong time it's given one hour before please help me what I am doing wrong.
The desired result is in London time, so 8:31 AM in this case.
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
public class CurrentUtcDate {
public static void main(String[] args) {
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC Time is: " + dateFormat.format(date));
}
}
Output
UTC Time is: 22-01-2018 13:14:35
You can check here https://www.quora.com/How-do-I-get-the-current-UTC-date-using-Java
As you need to you use Joda DateTime, you need to use formatter of Joda.
You are returning date with pattern "h:mm aa" so I assume you need to extract time from the date.
Below code should work:
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class MyDateCoonverter {
public static void main(String a[]) {
System.out.println(convertInDateTimeSecondTOJodaTime("2020-04-09T07:31:16Z"));
}
public static String convertInDateTimeSecondTOJodaTime(String dateTime) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime dt = formatter.parseDateTime(dateTime);
return dt.toString("h:mm aa", Locale.ENGLISH);
}
}
It gives output as:
7:31 AM
If you don't want to use any third party library & still want to extract only time from date, you can use Java's LocalTime.
If you are using Java 8 or newer, you should not use java.util.Date (deprecated) or Joda Time (replaced by the new DATE API of Java 8 with java.time package) :
public static void main(String[] args) {
String date = "2020-04-09T07:31:16Z";
String formatedDate = ZonedDateTime.parse(date).format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT));
System.out.println(formatedDate); //print "7:31 AM"
}
}
First, don’t handle date and time as strings in your program. Handle them as proper date-time objects. So but for all but the simplest throw-away programs you should not want a method that converts from a string in UTC to a string in London time in a different format.
So when you accept string input, parse into a DateTime object:
String stringInput = "2020-04-09T07:31:16Z";
DateTime dt = DateTime.parse(stringInput);
System.out.println("Date-time is: " + dt);
Output so far is:
Date-time is: 2020-04-09T07:31:16.000Z
I am exploiting the fact that your string is in ISO 8601 format, the default for Joda-Time, so we need no explicit formatter for parsing it.
Not until you need to give string output, convert your date and time to the desired zone and format into the desired string:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTime outputDateTime = dt.withZone(zone);
String output = outputDateTime.toString("h:mm aa");
System.out.println("Output is: " + output);
Output is: 8:31 AM
What went wrong in your code
Z in single quotes in your format pattern string is wrong. Z in your input string is an offset of 0 from UTC and needs to be parsed as an offset, or you are getting an incorrect result. Never put those quotes around Z.
withZoneRetainFields() is the wrong method to use for converting between time zones. The method name means that the date and hour of day are kept the same and only the time zone changed, which typically leads to a different point in time.
What happened was that your string was parsed into 2020-04-09T07:31:16.000+01:00, which is the same point in time as 06:31:16 UTC, so wrong. You next substituted the time zone to UTC keeping the time of day of 07:31:16. This time was then formatted and printed.
Do consider java.time
As Fabien said, Joda-Time has later been replaced with java.time, the modern Java date and time API. The Joda-Time home page says:
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time (JSR-310).
Links
Wikipedia article: ISO 8601
Joda-Time home

How to convert java.util.Date to soap suppported date format "yyyy-MM-dd'T'HH:mm:ss" with zone id

I am dealing with a situation where I want to convert java.util date into soap supported format with specific zone (Europe/Brussels)
I tried using Java 8 zone id feature but it seems it works well with instant dates only.
ZoneId zoneId = ZoneId.of("Europe/Brussels");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.now(),
zoneId);
GregorianCalendar calendar = GregorianCalendar.from(zonedDateTime);
String xmlNow = convertToSoapDateFormat(calendar);
calendar.add(Calendar.MINUTE, 61);
String xmlLater = convertToSoapDateFormat(calendar);
//Method for soap conversion
private String convertToSoapDateFormat(GregorianCalendar cal) throws DatatypeConfigurationException {
XMLGregorianCalendar gDateFormatted2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(
cal.get(Calendar.YEAR), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),
DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
return gDateFormatted2.toString();// + "Z";
}
I want lets say this date (2002-02-06) converted to this SOAP format 2002-02-06T08:00:00
You can use the SimpleDateFormat class with setTimezone method
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdfAmerica = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss");
sdfAmerica.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
String sDateInAmerica = sdfAmerica.format(new Date());
System.out.println(sDateInAmerica);
}
}
I'm not sure if this is the answer you are looking for, so tell me if I misunderstood your question. Then I'll delete the answer.
You can use the SimpleDateFormat class to achieve your goal. Create the format with by
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
And then format the date with the following call:
df.format(date);
java.time
I tried using Java 8 zone id feature but it seems it works well with
instant dates only.
Using java.time, the modern Java date and time API that came out with Java 8 and includes ZoneId, certainly is the recommended approach. And it works nicely. I cannot tell from your question what has hit you. If I understand correctly, DateTimeFormatter.ISO_OFFSET_DATE_TIME will give you the format you are after for your SOAP XML.
ZoneId zoneId = ZoneId.of("Europe/Brussels");
ZonedDateTime zdtNow = ZonedDateTime.now(zoneId);
String xmlNow = zdtNow.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
ZonedDateTime zdtLater = zdtNow.plusMinutes(61);
String xmlLater = zdtLater.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println("Now: " + xmlNow);
System.out.println("Later: " + xmlLater);
When I ran this code just now, the output was:
Now: 2019-10-21T13:56:37.771+02:00
Later: 2019-10-21T14:57:37.771+02:00

Unable to parse String using Java Date parser

I was parsing a datetime string using this: http://developer.android.com/reference/java/text/SimpleDateFormat.html but somehow i was getting runtime error on parsing: https://ideone.com/gpFqwp
Can anyone point me to my mistake here?
static String date = "2015-09-17T08:22:49Z";
public static DateFormat inputDatetimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public static DateFormat displayDateFormat = DateFormat.getDateTimeInstance();
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(displayDateFormat.format(inputDatetimeFormatter.parse(date)));
}
DateFormat inputDatetimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
See javadoc for SimpleDateFormat in Java 7
or use
DateFormat inputDatetimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
See javadoc for SimpleDateFormat in Java 6
here is a sample
Change inputDatetimeFormatter to new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");. Then it will run fine.
EDIT : What is the purpose of the Z at the end of your date string?
Is it just a letter that you always want to be there?
Then you will have to change inputDatetimeFormatter to the above.
If the purpose of Z is for the time zone then your date string is wrong (shouldn't contain Z but a time zone, e.g. -0800).
Then it would give :
static String date = "2015-09-17T08:22:49-0800"; // Replace -0800 by wanted time zone
public static DateFormat inputDatetimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); // Now you can use Z (instead of 'Z') to indicate that the time zone is following

Date with Timezone in Java

What is the Simple Date Format for "2014-01-02T23:03:30-05:00"?
I have googled and got the format only, yyyy-MM-dd'T'HH:mm:ssz. But this format is only working when my date format is without colon in the end "2014-01-02T23:03:30-0500".
Can anyone please advise on this?
If you use Java 7, you can replace the z by a X to allow for colon separator: yyyy-MM-dd'T'HH:mm:ssX.
See also the javadoc.
Before Java 7, you need to either parse it manually by first removing the colon or you can use an external library such as Jodatime or threeten.
There is the letter X for ISO 8601 timezone.
import java.text.*;
import java.util.*;
public class TimeZoneTest {
public static void main(final String[] args) throws ParseException {
final DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
final String string = "2014-01-02T23:03:30-05:00";
final Date date = format.parse(string);
System.out.println(date);
}
}
Use an X instead of the Z
docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
FYI, you can pass that string directly to a constructor in Joda-Time 2.3. No need for a formatter. Joda-Time uses that standard ISO 8601 format as its default, even tolerating the lack of a colon in the offset.
Instead of passing DateTimeZone.UTC as I did in my example code below, you would pass the specific time zone of your interest.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String string = "2014-01-02T23:03:30-0500";
DateTime dateTime = new DateTime( string, DateTimeZone.UTC );
System.out.println( "dateTime: " + dateTime );
When run:
dateTime: 2014-01-03T04:03:30.000Z

Converting Date time format in Java

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?
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.)
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);
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" );
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);
}
}
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"));
}
}

Categories