I have a String of western date.I want is to have it in Japanese format.
String date = "2015-06-01";
I want is to have it in Japanese format. Please help me!
output = 平成27年6月1日
You can use my lib Time4A which is also available for lower Android API levels and then use its JapaneseCalendar:
String input = "2015-06-01";
PlainDate gregorian = Iso8601Format.EXTENDED_DATE.parse(input);
ChronoFormatter<JapaneseCalendar> f = // immutable, so you can make it static
ChronoFormatter.ofStyle(DisplayMode.MEDIUM, Locale.JAPANESE, JapaneseCalendar.axis());
String output = f.print(gregorian.transform(JapaneseCalendar.axis()));
System.out.println(output); // 平成27年6月1日
I have also done an experiment with the java.time-package which is available since API level 26, but could not quickly find a way to produce the format you want:
DateTimeFormatter dtf =
DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.JAPAN)
.withChronology(JapaneseChronology.INSTANCE);
JapaneseDate japaneseDate = JapaneseDate.from(LocalDate.parse(input));
System.out.println(dtf.format(japaneseDate)); // H27.06.01
The numbers are correct but it does not use Japanese symbols and letters, despite of the fact that I specified the Japan locale. Maybe a workaround using the builder and a hand-made pattern will help further. Note that my experiment was executed in a Java-8-environment. Maybe Android or newer Java versions are different?!
As a minor supplement to the answer by Meno Hochschild, if you want to use java.time for this, you may do it in this way:
DateTimeFormatter japaneseEraDtf = DateTimeFormatter.ofPattern("GGGGy年M月d日")
.withChronology(JapaneseChronology.INSTANCE)
.withLocale(Locale.JAPAN);
String date = "2015-06-01";
LocalDate gregorianDate = LocalDate.parse(date);
JapaneseDate japaneseDate = JapaneseDate.from(gregorianDate);
System.out.println(japaneseDate.format(japaneseEraDtf));
Output is:
平成27年6月1日
I think it was what you asked for.
If I have understood correctly, java.time does not format the first year of an era in the way usually expected by Japanese, which Meno Hochschild’s Time4A library does, so all things being equal you will prefer his answer.
I have stolen the formatter from this answer by buræquete.
LocalDate localDate = LocalDate.now();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy/MM/dd").withChronology(IsoChronology.INSTANCE)
.withLocale(Locale.ENGLISH);
DateTimeFormatter japanDateFormat = DateTimeFormatter.ofPattern("yyyy年MM月dd日")
.withChronology(IsoChronology.INSTANCE)
.withLocale(Locale.JAPAN);
}
System.out.println(localDate.format(dateFormat));
System.out.println(localDate.format(japanDateFormat));
Output is:
2022/06/15
2022年06月15日
Related
I have one time string format like yyyy-MM-dd'T'HH:mm:ss.SSSSSS with the time zone "GMT+05:30". I need to convert this format in yyyy-MM-dd'T'HH:mm:ss.SSS'Z' format with different time zone - "GMT0:00". I write below funtion to convert time string with different timezone. It works fine but can't change time.
public static String getUTCDate(String dateString) {
String oldDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS";
String newDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
String result = "";
SimpleDateFormat simpleDateFormatOld;
SimpleDateFormat simpleDateFormatNew;
try {
simpleDateFormatOld = new SimpleDateFormat(oldDateFormat,Locale.US);
simpleDateFormatNew = new SimpleDateFormat(newDateFormat,Locale.US);
simpleDateFormatNew.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
result = simpleDateFormatNew.format(simpleDateFormatOld.parse(dateString));
}
catch(Exception e) {
ExceptionHandler.handleException(e);
}
return result;
}
Example: I passed 2019-07-11T21:28:02.8469576 date time string. But in return I got 2019-07-11T21:28:02.846Z date time string without changing the time.
How can I update time of string?
Try this:
public static String getUTCDate(String dateString) {
String oldDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS";
String newDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
String result = "";
SimpleDateFormat simpleDateFormatOld;
SimpleDateFormat simpleDateFormatNew;
try {
simpleDateFormatOld = new SimpleDateFormat();
simpleDateFormatOld.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
simpleDateFormatOld.applyPattern(oldDateFormat);
simpleDateFormatNew = new SimpleDateFormat(newDateFormat, Locale.US);
result = simpleDateFormatNew.format(simpleDateFormatOld.parse(dateString));
}
catch(Exception e) {
e.printStackTrace();
}
return result;
}
It worked for me. It just sets the timezone of the simpleDataFormatOld object before applying the date pattern to it.
For most purposes you should not want to convert a point in time from one string format in one time zone into a different string format in a different time zone. In your program keep your date and time in proper date-time objects, not strings (just like you wouldn’t keep an integer or floating-point value in a string). If you just need the point in time (not the original GMT offset, +05:30), the Instant class is the correct one to use. When your program accepts a string input, parse and convert it to Instant first thing and keep it as such. Only when you need to give string output, format the time back into a string and pass it out.
java.time and ThreeTenABP
Parse and convert input
ZoneId originalZone = ZoneId.of("Asia/Kolkata");
Instant time = LocalDateTime.parse("2019-07-11T21:28:02.8469576")
.atZone(originalZone)
.toInstant();
System.out.println(time);
The converted time prints as:
2019-07-11T15:58:02.846957600Z
For most purposes, don’t give time zone as a naked GMT offset. A named time zone better explains to the reader why this zone was chosen and is more future-proof in case the offset is changed (which happens more often than you would think). I am exploiting the fact that your string is in ISO 8601 format. In this case we don’t need to supply an explicit formatter. BTW your example string has 7 decimals on the seconds and your oldDateFormat seems to want 6. It doesn’t matter here since LocalDateTime.parse accepts anything from 0 through 9 decimals.
Format output
The output you asked for is a different variant of ISO 8601. The output above resembles pretty well because it too is ISO 8601, only there are too many decimals. So let’s apply an explicit formatting this time:
ZoneOffset newOffset = ZoneOffset.UTC;
DateTimeFormatter newFormatter = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral('T')
.appendPattern("HH:mm:ss.SSSX")
.toFormatter();
String formattedUtcDateTime = time.atOffset(newOffset).format(newFormatter);
System.out.println(formattedUtcDateTime);
2019-07-11T15:58:02.846Z
We see that java.time, the modern Java date and time API, forces us to specify the time zone offset, so forgetting to do so (like it seems you did in the code in the question, causing the unexpected output) simply is not possible.
I recommend against SimpleDateFormat and TimeZone
The date-time classes that you tried to use, SimpleDateFormat and TimeZone, are poorly designed and long outdated, the former in particular notoriously troublesome. Also there is no way that SimpleDateFormat can parse 6 or 7 decimals on the seconds correctly; it supports only milliseconds, exactly three decimals. Instead I am using java.time, the modern Java date and time API. I find it so much nicer to work with.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
EDIT: Try this method:
public static String getUTCDate(String dateString) {
Log.d(TAG,"input : "+dateString);
String oldDateFormat = "yyyy-MM-dd'T'HH:mm:ss";
String newDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
String result = "";
SimpleDateFormat simpleDateFormatOld;
SimpleDateFormat simpleDateFormatNew;
try {
simpleDateFormatOld = new SimpleDateFormat(oldDateFormat, Locale.US);
simpleDateFormatNew = new SimpleDateFormat(newDateFormat,Locale.US);
simpleDateFormatOld.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
simpleDateFormatNew.setTimeZone(TimeZone.getTimeZone("GMT0:00"));
result = simpleDateFormatNew.format(simpleDateFormatOld.parse(dateString));
}
catch(Exception e) {
ExceptionHandler.handleException(e);
}
return result;
}
There are 2 changes:
1. Set time zone for New format also.
simpleDateFormatNew.setTimeZone(TimeZone.getTimeZone("GMT0:00"));
Remove milliseconds pattern from oldDateFormat.
String oldDateFormat = "yyyy-MM-dd'T'HH:mm:ss";
I have solved this issue by adding time zone for oldDateFormat also.
For example:
simpleDateFormatOld.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
simpleDateFormatNew.setTimeZone(TimeZone.getTimeZone("GMT+0:00"));
I recently started coding my really first Android project using Android Studio 3.1.2 and SDK 19.
One of my Objects has Date attributes. At some points I want to display the whole date time or parts of it in a TextView. So I tried it the rookie way and called toString() on my Date.
However the displayed text contains elements I didn't define in the SingleDateFormat pattern I used to create the Date Object.
This is how I create the Date on myObject:
Date date1;
Date date2;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date1 = format.parse(json.getString("date_1"));
dtae2 = format.parse(json.getString("date_2"));
} catch(ParseException e) {
//error handling stuff
e.printStackTrace();
}
This is where I want to display the Date on a View:
myTextView.setText("First appearance logged at " + myObject.getDate1().toString());
I expected a String like 2018-08-16 12:14:42 to be displayed. Instead what I get is Thu Aug 12:14:42 GMT +02:00 2018. This seems to be another DateFormat and ignoring my custom pattern.
So my question is, if there's a way to manipulate the output of toString(), so the Date gets displayed in the way I defined in the pattern. Can I somehow pass the pattern to the toString() method?
EDIT
I changed the attributes of my Objects to String type, though it's way easier for presenting. The reason to convert them into a Date is, that I need to calculate the duration between the two guys, but that's not a problem i can't solve. Thanks to the community.
According to your need, you can just use json.getString("date_1").
You don't need to set extra logics. Parsing is needed when you want to convert String date to Date object for some calculation.
If you want to change format of received date then use this method.
changeStringDateFormat(json.getString("date_1"), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");
Just put this method inside your Util.
public String changeStringDateFormat(String date, String inputDateFormat, String outPutDateFormat) {
Date initDate = null;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(inputDateFormat);
initDate = simpleDateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat outputFormatter = new SimpleDateFormat(outPutDateFormat);
String parsedDate = outputFormatter.format(initDate);
return parsedDate;
}
See Java Date Doc, It returns string from default format.
public String toString()
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
Simply Write this code snippet
JAVA FILE
public class MainActivity extends AppCompatActivity {
TextView my_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_text = findViewById(R.id.my_text);
String pattern = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(new Date());
Toast.makeText(getApplicationContext(), "" + date, Toast.LENGTH_SHORT).show();
my_text.setText("Your Date is : " + date);
}
}
XML FILE
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="mydemo.com.anew.MainActivity">
<TextView
android:id="#+id/my_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
See output:
See Screenshot of output same like your requirement get a current date:
Refer this Tutorial
Hope this may help to you
tl;dr
Use the modern java.time classes instead of the terrible legacy Date & SimpleDateFormat classes.
myJavaUtilDate // Never use `java.util.Date`.
.toInstant() // Convert from legacy class to modern replacement. Returns a `Instant` object, a moment in UTC.
.atOffset( // Convert from the basic `Instant` class to the more flexible `OffsetDateTime` class.
ZoneOffset.UTC // Constant defining an offset-from-UTC of zero, UTC itself.
) // Returns a `OffsetDateTime` object.
.format( // Generate a `String` with text representing the value of this `OffsetDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // Pre-defined formatter stored in this constant.
) // Returns a `String` object.
.replace( "T" , " " ) // Replace the standard `T` in the middle with your desired SPACE character.
2018-08-16 10:14:42
java.time
You are using terrible old classes that were supplanted years ago by the java.time classes.
If handed a java.util.Date object, immediately convert to java.time.Instant. Both represent a moment in UTC. Instant has a finer resolution of nanoseconds rather than milliseconds.
To convert between the legacy and modern classes, look to new conversion methods added to the old classes.
Instant
Instant instant = myJavaUtilDate.toInstant() ; // New method on old class for converting to/from java.time classes.
ISO 8601
To generate a String with text in standard ISO 8601 format similar to your desired format, call toString.
String output = instant.toString() ; // Generate text in standard ISO 8601 format.
Elapsed time = Duration
By the way, to calculate elapsed time, use the Duration classes. Pass a pair of Instant objects to calculate the number of 24-hour "days", hours, minutes, and seconds elapsed.
Duration d = Duration.between( start , stop ) ; // Calc elapsed time.
2018-08-16T10:14:42Z
OffsetDateTime
For other formatting, convert from the basic Instant class to the more flexible OffsetDateTime class.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
odt.toString(): 2018-08-16T10:14:42Z
DateTimeFormatter
Your desired format is close to the predefined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME. Just replace the T in the middle with a SPACE.
String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " ) ;
2018-08-16 10:14:42
ZonedDateTime
Keep in mind that we are only looking at UTC so far. For any given moment, the date and the time-of-day both vary around the globe by zone.
If you want to see that same moment through the lens of the wall-clock time used by the people of a certain region (a time zone), then apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-08-16T11:14:42+01:00[Africa/Tunis]
You can use the same formatter as seen above to generate a string in your desired format.
String output = zdt.format( f ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You need to use SimpleDateFormat something like this:
String myFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
myTextView.setText("First appearance logged at " + sdf.format(date1));
In my project I've been formatting using the format() function, like so:
myTextView.setText("First appearance logged at " + format.format(myObject.getData1()));
I hope that helps.
I got a Problem when converting a Date in my Android App.
My Problem is that I got two different Formats of the Date.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
DateFormat formatter_date = new SimpleDateFormat("dd.MMM.yyyy");
Date myDate = null;
try {
myDate = dateFormat.parse("28.10.2015");
} catch (ParseException e) {
e.printStackTrace();
}
formatter_date.format(myDate,"dd.MM.yyyy"))
txtDate.setText(formatter_date.format(myDate,"dd.MM.yyyy")));
I want to have the date formatted as 28.Oct.2015 on a device set to English language, as 28.Okt.2015 in German, etc. So always one dot before and after the month abbreviation. When language is set to English it returns 28.Oct.2015 as it should, however, when Language is set to German it returns 28.Okt..2015 with two dots between Okt and 2015.
Is there any solution to handling this?
I should like to challenge what you are asking for. Of course you can have it, as your own answer already shows. But do you want it?
Use the built-in localized formats
Java has localized formats for all available locales (I think it’s all, in any case it’s many). I suggest you use these rather than your own idea of what a localized date should look like. While 28.Okt.2015 is probably commonplace in Austria and other German-speaking places, English-speaking people are not used to the dots in your format, and I would suspect that some people in the world will find it more or less strange.
I suggested in a comment that you add ThreeTenABP to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with. Now I am taking my own medicine:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
LocalDate myDate = LocalDate.of(2015, Month.OCTOBER, 28);
System.out.println(myDate.format(dateFormatter));
Output in different locales include:
German: 28.10.2015
UK English: 28 Oct 2015
French: 28 oct. 2015
It’s not what you asked for. And you may meet objections, but that will happen no matter which format you choose because many people have their own ideas about the proper formatting for their locale. It’s pretty standardized, though, so consider it.
Edit: where did the LocalDate come from?
I understood that you were converting from a string like "28.10.2015". Converting this to a LocalDate is straightforward when you know how:
DateTimeFormatter numericDateFormatter = DateTimeFormatter.ofPattern("dd.MM.uuuu");
LocalDate myDate = LocalDate.parse("28.10.2015", numericDateFormatter);
Only if you got a java.util.Date from a legacy API that you cannot change or do not want to change just now, first thing convert it to the modern Instant type and do further conversions from there:
LocalDate myDate = oldfashionedJavaUtilDate.toInstant()
.atZone(ZoneId.of("Europe/Vienna"))
.toLocalDate();
Since this is a time zone sensitive operation, I recommend you specify an explicit time zone. You may use the JVM’s time zone setting by specifying ZoneId.systemDefault(), but be aware that this is fragile: the JVM setting may be changed under your feet by other parts of your program or other programs running in the same JVM.
What you asked for
The java.time edition of what you asked for is pretty similar to the code in your own answer:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd");
DateTimeFormatter monthFormatter = DateTimeFormatter.ofPattern("MMMM");
DateTimeFormatter yearFormatter = DateTimeFormatter.ofPattern("uuuu");
LocalDate myDate = LocalDate.of(2015, Month.OCTOBER, 28);
String dayOfMonth = myDate.format(dateFormatter);
String monthName = myDate.format(monthFormatter);
if (monthName.length() > 3) {
monthName = monthName.substring(0, 3);
}
String year = myDate.format(yearFormatter);
String formattedDate = dayOfMonth + '.' + monthName + '.' + year;
System.out.println(formattedDate);
Output in the same locales as above:
German: 28.Okt.2015
UK English: 28.Oct.2015
French: 28.oct.2015
There is a much shorter way to obtain the same, though:
String formattedDate = String.format("%1$td.%2$.3s.%1$tY",
myDate,
myDate.getMonth().getDisplayName(TextStyle.FULL, Locale.getDefault()));
It’s harder to read. It took me a number of attempts to get the format string %1$td.%2$.3s.%1$tY exactly right. And it will surprise those maintaining your code if they are used to DateTimeFormatter for formatting dates (and times). So I don’t really recommend it, but the choice is yours.
With another date I got the following output in French locale:
08.jui.2018
No French-speaking person, nor anyone else for that matter, will know whether this date was in June (juin) or July (juillet). In 57 of the available locales in my JVM, all 12 months of the year begin with the same three letters. Such locales include Tibetan, Swahili, Somali, Cornish, Scottish Gaelic and Vietnamese. In these languages nobody will be able to tell any months apart. Please think twice.
Links
Oracle tutorial: Date Time, explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
SimpleDateFormat dateFormat = new SimpleDateFormat(String pattern, Locale locale);
has another constructor with Locale change Locale.ENGLISH for date to be set in English. You can check other Locale options. I generally use Locale.getDefault() to display date in user's prefered language.
Thanks for help but this solution works best for me
DateFormat formatter_month = new SimpleDateFormat("MMMM"); //Get Whole Name of Month
DateFormat formatter_day = new SimpleDateFormat("dd."); //Get Day + Dot(2 digits)
DateFormat formatter_year = new SimpleDateFormat(".yyyy"); //Get Dot + Year(4 digits)
String str_date = formatter_day.format(date)+ //Day
formatter_month.format(date).substring(0,3)+ //Month
formatter_year.format(date); //Year
Every time I try to get the current time (I have a button for that, lets call it "botonGuardarEstado") I get the same hours and minutes. What I have noted is that the time I got is the time when I opened the app. What I mean is, if I opened the app at 7:10 a.m. and press the button at 7:12 a.m., I get 7:10 a.m. Here is my code:
DateFormat formatoFecha = new SimpleDateFormat("HH:mm dd/MM/yyyy");
String fecha = formatoFecha.format(Calendar.getInstance().getTime());
I am not getting weird values like different years or anything like that, and the format works well, the problem is that i get the same hours:minutes everytime i push the button. I alredy tried different ways of getting the date and time, things like Date(), or even getting only the hours and minutes using something like this
Calendar cal = Calendar.getInstance();
int mins = cal.get(Calendar.MINUTE);
but still got the same values.
I have the following class
private class InfoArchivo {
String temperatura, humedad, gas, humo, iluminacion, riego, ventilacion, fecha;
public InfoArchivo(String temperatura, String humedad, String gas, String humo, String iluminacion, String riego, String ventilacion, String fecha){
this.temperatura = temperatura;
this.humedad = humedad;
this.gas = gas;
this.humo = humo;
this.iluminacion = iluminacion;
this.riego = riego;
this.fecha = fecha;
if(!ventilacion.equals("0"))
this.ventilacion = "1";
else
this.ventilacion = "0";
}
I have an array of instances of that class. What i am trying to do is write a csv file using the array. Every other data (temperatura, humedad, etc) is correct. The only thing causing trouble is the date (fecha). The creation of the csv file is done until i press another button. When i press the botonGuardarEstado button i get the date, make an instance of the class InfoArchivo and add it to the array
EDIT: Also tried with this but still have the same issue:
Instant instant = Instant.now();
ZoneId zoneId = ZoneId.of("America/Guatemala");
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, zoneId);
DateTimeFormatter formato = DateTimeFormatter.ofPattern("HH:mm dd/MM/yyyy");
String fecha = zdt.format(formato);
Not a date-time problem
Your code as shown is correct.
So your problem must be happening elsewhere in your app. Perhaps you are not correctly feeding the new String (fecha) to the user interface. Or perhaps you need to do something to refresh the display of that new String’s value. We cannot help you further as you did not provide that other code.
java.time
By the way, you are using outmoded classes. The old date-time classes that have proven to be so confusing and troublesome have been supplanted by the java.time framework. See the Oracle Tutorial.
Java 8 and later: The java.time framework is built-in.
Java 7 & 6: Use the backport of java.time.
Android: Use this wrapped version of that backport.
Instant
An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.
Instant instant = Instant.now(); // Current moment in UTC.
Time Zone
Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVM’s current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Generating Strings
You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.
ISO 8601
You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.
String output = instant.toString();
2016-03-19T05:54:01.613Z
Custom format
Or specify your own particular formatting pattern with the DateTimeFormatter class.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );
Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.
formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );
Localizing
Better yet, let java.time do the work of localizing automatically.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) ); // Or Locale.CANADA_FRENCH and so on.
Im using Joda Time to format the dateTime as following:
DateTimeFormatter dateFormatter = DateTimeFormat.longDate();
String startTimeStr = dateFormatter.print(localStartTime);
The variables's values are:
localStartTime={org.joda.time.LocalDateTime#830018681648}"2013-04-06T23:54:35.000"
startTimeStr={java.lang.String#830018688880}"2013年4月6日"
Problem is how could I obtain the locale date format on month and day? I have tried the following codes:
DateTimeFormatter monDayFormatter = DateTimeFormat.forPattern("MMMd");
String startTimeStr = monDayFormatter.print(localStartTime);
and the variables's values are:
localStartTime={org.joda.time.LocalDateTime#830018681648}"2013-04-06T23:54:35.000"
startTimeStr={java.lang.String#830018683220}"4月6"
What I expected startTimeStr is 4月6日. Here the Chinese character 日 = Day.
I do not want to hard code the pattern to "MMMd日", because it should adjust itself according to the current locale information. Any help will be appreciated.
On the website of unicode consortium, you will find in Chinese CLDR repository for example entries like follows (calendar type = gregorian):
<dateFormats>
<dateFormatLength type="full">
<dateFormat>
<pattern>y年M月d日EEEE</pattern>
</dateFormat>
</dateFormatLength>
<dateFormatLength type="long">
<dateFormat>
<pattern>y年M月d日</pattern>
</dateFormat>
</dateFormatLength>
<dateFormatLength type="medium">
<dateFormat>
<pattern>y年M月d日</pattern>
</dateFormat>
</dateFormatLength>
<dateFormatLength type="short">
<dateFormat>
<pattern>yy/M/d</pattern>
</dateFormat>
</dateFormatLength>
</dateFormats>
Internally every localized date format either in JodaTime or in JDK dateformat classes will be translated to such a pattern - including literals like "日". CLDR does not define a month-day-only-format, but this is just a part of a general year-month-day-format, so if you use as replacement for
DateTimeFormatter dateFormatter = DateTimeFormat.longDate().withLocale(Locale.CHINESE);
LocalDateTime localStartTime = new LocalDateTime(2013,4,6,23,54,35);
String startTimeStr = dateFormatter.print(localStartTime);
System.out.println(startTimeStr); // output: 2013年4月6日
this code:
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("M月d日");
LocalDateTime localStartTime = new LocalDateTime(2013,4,6,23,54,35);
String startTimeStr = dateFormatter.print(localStartTime);
System.out.println(startTimeStr); // output: 4月6日
then you get what you want. Although you write:
I do not want to hard code the pattern to "MMMd日"
that is pretty much the same procedure as done internally by libraries. So the pattern itself is localized by choosing the appropriate literals. There is no way to extract from CLDR a localized date pattern without year. If you want this, then you have to manage your own set of localized month-day-patterns for different locales, maybe in a Map<Locale, String>.
Update from 2016-12-06:
The situation not having a generic month-day-pattern for any locale has not changed for Joda-Time. Unfortunately the official successor of Joda-Time, the JSR-310 (java.time-package) does not manage it well, too, see the JDK-issue 8168532. This was reason enough for me to find a solution for my own time library Time4J in the mean-time. A close analysis of CLDR data has shown that there are other date formats available for many languages, but in a different section and accessible via a group of fields. The keys "Md", "MMMd" and "MMMMd" are relevant for your use-case. Example in Time4J (which should hopefully be supported by JSR-310, too, in a future release):
PlainTimestamp tsp = Iso8601Format.EXTENDED_DATE_TIME.parse("2013-04-06T23:54:35.000");
AnnualDate ad = AnnualDate.of(tsp.getMonth(), tsp.getDayOfMonth());
ChronoFormatter<AnnualDate> chinese =
ChronoFormatter.ofStyle(DisplayMode.LONG, Locale.CHINESE, AnnualDate.chronology());
ChronoFormatter<AnnualDate> english =
ChronoFormatter.ofStyle(DisplayMode.LONG, Locale.ENGLISH, AnnualDate.chronology());
System.out.println(chinese.format(ad)); // 4月6日
System.out.println(english.format(ad)); // Apr 6
It is also worth to note that the locale cannot be changed after construction of formatter in a sensible way because the localized pattern structure will be freezed during construction and is no longer sensible for later changes of locale. This will be improved in future release, however.
Here you go :
Calendar calendar = Calendar.getInstance();
SimpleDateFormat day_week = new SimpleDateFormat("EEEE");
SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
Date d = new Date();
String dayOfTheWeek = day_week.format(d);
String month = month_date.format(calendar.getTime());
Hope it helps.
Actually Android provides a helper class to deal with UTS #35 formatting, android.text.format.DateFormat.
In particular for this case, DateFormat.getBestDateTimePattern(locale, skeleton) since API Level 18.
So we can simplify things like this:
String bestFormat = DateFormat.getBestDateTimePattern(Locale.getDefault(), "MMMd");
String formatted = DateFormat.format(bestFormat, System.currentTimeMillis()).toString();
formatted would be "12月19日".
The behavior is confirmed on Android Q and Android O.