How to show date without year based on locale in Java? [duplicate] - java

This question already has an answer here:
Localize string from `MonthDay` or `YearMonth` classes in java.time? [duplicate]
(1 answer)
Closed 3 years ago.
I use DateFormat and locale to show Day and Month. DateFormat supports MEDIUM, LONG, FULL all have a year.I only want to show month and day.
I tried to use SimpleDateFormat, but SimpleDateFormat defined the order of month and day. In different countries, date format is different. I don't want to define the order of month and day. I hope the date format is decided by locale.
Here is my code and how can I remove year from the date?
Locale myLocale =Locale.FRANCE;
DateFormat localFormatter = DateFormat.getDateInstance(DateFormat.MEDIUM, myLocale);
String localDate = localFormatter.format(date);
I tried the following locale and print the date on the right:
Locale myLocale =Locale.FRANCE; localDate=1 avr. 2018
Locale myLocale =Locale.CHINA; localDate=2018-4-1
Locale myLocale =Locale.JAPAN; localDate=2018/04/01

A localized DateFormat may or may not be a SimpleDateFormat, so you can’t be certain it will have a pattern. However, you can obtain a localized DateTimeFormatter pattern, and strip the year from that:
public static Format createMonthDayFormat(FormatStyle style,
Locale locale) {
String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
style, null, Chronology.ofLocale(locale), locale);
pattern = pattern.replaceFirst("\\P{IsLetter}+[Yy]+", "");
pattern = pattern.replaceFirst("^[Yy]+\\P{IsLetter}+", "");
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(pattern, locale);
return formatter.toFormat();
}
There is a catch, however. The returned Format cannot format Date or Calendar objects. It expects Temporal objects like LocalDate or ZonedDateTime. You will need to convert a java.util.Date to such an object:
Format format = createMonthDayFormat(FormatStyle.SHORT, Locale.getDefault());
Date date = new Date();
String text = format.format(
date.toInstant().atZone(ZoneId.systemDefault()));

Related

How to decode the date in Android? - DATETIMESTAMP [duplicate]

This question already has answers here:
Android: Compare time in this format `yyyy-mm-dd hh:mm:ss` to the current moment
(5 answers)
Conversion of a date to epoch Java [duplicate]
(4 answers)
How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
(16 answers)
Closed 2 years ago.
The following code gave me Datetimestamp as [ 2020-07-183 17:07:55.551 ]. The issue is with "Day" in Datetimestamp, which has three digits. How to format currentTimeMillis into the right format for day of month?
public String Datetimesetter(long currentTimeMillis, SimpleDateFormat dateFormat) {
dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS.SSS");
// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(currentTimeMillis);
return dateFormat.format(calendar.getTime());
}
SOLUTION WHICH WORKED FOR ME:
Please visit this link.
This is for the case you are supporting Apps from API level 26 (native support of java.time) or you are willing / allowed to use a backport library of the same functionality.
Then you can use a correct / matching pattern (one that considers three-digit days) like this:
public static void main(String[] args) {
// mock / receive the datetime string
String timestamp = "2020-07-183 17:07:55.551";
// create a formatter using a suitable pattern (NOTE the 3 Ds)
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-DDD HH:mm:ss.SSS");
// parse the String to a LocalDateTime using the formatter defined before
LocalDateTime ldt = LocalDateTime.parse(timestamp, dtf);
// and print its default String representation
System.out.println(ldt);
}
which outputs
2020-07-01T17:07:55.551
So I guess the day of year no. 183 was actually July 1st.
your date format is incorrect
dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:MM:SS.SSS");
change to this
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS.SSS");

How to convert a string date to a different timezone using Java 8 [duplicate]

I want to convert a String Date into a DateTime object for a particular timezone and in a particular format. How can I do it ?
String Date can be in any format used in the world. Example MM-DD-YYYY, YYYY-MM-DD, MM/DD/YY
, MM/DD/YYYY etc. TimeZone can be any legal timezone specified by the user.
Example - convert YYYY-MM-DD into MM/DD/YY for the Pacific Timezone.
Use DateTimeFormatterBuilder to build a formatter that is able to parse/format multiple DateTimeFormats, and set the resulting DateTimeFormatter to use a specified DateTimeZone:
DateTimeParser[] parsers = {
DateTimeFormat.forPattern("MM-dd-yyyy").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd").getParser(),
DateTimeFormat.forPattern("MM/dd/yyyy").getParser(),
DateTimeFormat.forPattern("yyyy/MM/dd").getParser()
};
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.append(null, parsers)
.toFormatter()
.withZone(DateTimeZone.UTC);
DateTime dttm1 = formatter.parseDateTime("01-31-2012");
DateTime dttm2 = formatter.parseDateTime("01/31/2012");
DateTime dttm3 = formatter.parseDateTime("2012-01-31");
To format a given DateTime you can just use dttm1.toString("yyyy-MM-dd")).

Format time from miliseconds to show only the date [duplicate]

This question already has answers here:
Java Date Format for Locale
(2 answers)
Closed 9 years ago.
Sorry if my question has already been answered, but I can't really find what I am looking for.
So I have this time "1228061700000" and I want to convert it to show only the date, like this 17/6/08.
It would also be good to check for the locale, so for US locale the format to be like this 6/17/08 and for european locale to be 17/6/08... How can I do it?
Use a DateFormat:
DateFormat f = DateFormat.getDateInstance(DateFormat.SHORT, Locale.ENGLISH);
String result = f.format(new Date(millis));
long milliSeconds=1228061700000l;
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //change your date time formate as required
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
System.out.println(formatter.format(calendar.getTime()));
DateFormat.getDateInstance(int style, Locale aLocale)This displays the current date in a locale-specific way.
So, you can try:
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourDate);
In this case you can choose what type of yourDate is.
Your locate can be changed to Locale.UK Locale.US and etc.

Date converter in JAVA [duplicate]

This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Closed 9 years ago.
I have date like Tue Mar 19 00:41:00 GMT 2013, how to convert it to 2013-03-19 06:13:00?
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = bdate;
Date ndate = formatter.parse(formatter.format(date));
System.out.println(ndate);
gives the same date.
Use two SimpleDateFormat objects with appropriate formats and use the first to parse the string into a date and the second to format the date into a string again.
As the first answer says. First parse your date with SimpleDateFormat like this:
Date from = new SimpleDateFormat("E M d hh:mm:ss z yyyy").parse("Tue Mar 19 00:41:00 GMT 2013");
Then use that to format the resulting date object with another instance of SimpleDateFormat like this:
String to = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(from);
See the javadoc of SimpleDateFormat here. Hope that helps.
One major thing that the others have left out is dealing with the timezone (TZ). Anytime you use a SimpleDateFormat to go to/from a string representation of the date, you really need to be aware of what TZ you're dealing with. Unless you explicitly set the TZ on the SimpleDateFormat, it will use the default TZ when formatting/parsing. Unless you only deal with date strings in the default timezone, you'll run into problems.
Your input date is representing a date in GMT. Assuming that you also want the output to be formatted as GMT, you need to make sure to set the TZ on the SimpleDateFormat:
public static void main(String[] args) throws Exception
{
String inputDate = "Tue Mar 19 00:41:00 GMT 2013";
// Initialize with format of input
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
// Configure the TZ on the date formatter. Not sure why it doesn't get set
// automatically when parsing the date since the input includes the TZ name,
// but it doesn't. One of many reasons to use Joda instead
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse(inputDate);
// re-initialize the pattern with format of desired output. Alternatively,
// you could use a new SimpleDateFormat instance as long as you set the TZ
// correctly
sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
}
Use SimpleDateFormat in this way:
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = new Date();
System.out.println(formatter.format(date));
If you do any calculations or parsing with dates please use JodaTime because the standard JAVA date support is really buggy

SimpleDateFormat pattern based on locale, but forcing a 4-digit year

I need to build a date format like dd/MM/yyyy. It's almost like DateFormat.SHORT, but contains 4 year digits.
I try to implement it with
new SimpleDateFormat("dd//MM/yyyy", locale).format(date);
However for US locale the format is wrong.
Is there a common way to format date that changes pattern based on locale?
Thank you
I would do it like this:
StringBuffer buffer = new StringBuffer();
Calendar date = Calendar.getInstance();
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
FieldPosition yearPosition = new FieldPosition(DateFormat.YEAR_FIELD);
StringBuffer format = dateFormat.format(date.getTime(), buffer, yearPosition);
format.replace(yearPosition.getBeginIndex(), yearPosition.getEndIndex(), String.valueOf(date.get(Calendar.YEAR)));
System.out.println(format);
Using a FieldPosition you don't really have to care about wheter the format of the date includes the year as "yy" or "yyyy", where the year ends up or even which kind of separators are used.
You just use the begin and end index of the year field and always replace it with the 4 digit year value and that's it.
java.time
Here’s the modern answer. IMHO these days no one should struggle with the long outdated DateFormat and SimpleDateFormat classes. Their replacement came out in the modern Java date & time API early in 2014, the java.time classes.
I am just applying the idea from Happier’s answer to the modern classes.
The DateTimeFormatterBuilder.getLocalizedDateTimePattern method generates a formatting pattern for date and time styles for a Locale. We manipulate the resulting pattern string to force the 4-digit year.
LocalDate date = LocalDate.of( 2017, Month.JULY, 18 );
String formatPattern =
DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT,
null,
IsoChronology.INSTANCE,
userLocale);
formatPattern = formatPattern.replaceAll("\\byy\\b", "yyyy");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(formatPattern, userLocale);
String output = date.format(formatter);
Example output:
For Locale.US: 7/18/2017.
For each of UK, FRANCE, GERMANY and ITALY: 18/07/2017.
DateTimeFormatterBuilder allows us to get the localized format pattern string directly, without getting a formatter first, that’s convenient here. The first argument to getLocalizedDateTimePattern() is the date format style. null as second argument indicates that we don’t want any time format included. In my test I used a LocalDate for date, but the code should work for the other modern date types too (LocalDateTime, OffsetDateTime and ZonedDateTime).
I have similar way to do this, but I need to get the locale pattern for the ui controller.
So here's the code
// date format, always using yyyy as year display
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT, locale);
SimpleDateFormat simple = (SimpleDateFormat) dateFormat;
String pattern = simple.toPattern().replaceAll("\\byy\\b", "yyyy");
System.out.println(pattern);
Can you not just use java.text.DateFormat class ?
DateFormat uk = DateFormat.getDateInstance(DateFormat.LONG, Locale.UK);
DateFormat us = DateFormat.getDateInstance(DateFormat.LONG, Locale.US);
Date now = new Date();
String usFormat = us.format(now);
String ukFormat = uk.format(now);
That should do what you want to do.

Categories

Resources