I need to set calendar to next week's monday. My code works on Android 9.0 but on Android 6.0 it works only while debugging.
Problem is with Calendar.set(..) functions, they just don't work. For example calendar.set(Calendar.WEEK_OF_YEAR, 17) won't change calendar week to 17, but when it is debugging it will change it to 17.
Here is my code:
Calendar mcurrentTime = Calendar.getInstance(Locale.GERMANY);
if(AppHelper.getInstance().getNextWeek() != 0){
mcurrentTime.set(Calendar.WEEK_OF_YEAR,
AppHelper.getInstance().getNextWeek());
mcurrentTime.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
}
weekNumberTv.setText(mcurrentTime.get(Calendar.WEEK_OF_YEAR)+"");
Android 9.0 weekNumberTv shows 17
Android 6.0 weekNumberTv shows 16
If start debugging mode
Android 6.0 weekNumberTv shows 17
To do time calculations in versions prior to 7.0 sadly you will have to use JavaTime package or its backport.
Implement ThreeTen Android Backport library:
implementation 'com.jakewharton.threetenabp:threetenabp:1.2.0'
https://github.com/JakeWharton/ThreeTenABP
Then initialize it in onCreate method.
AndroidThreeTen.init(this)
Make sure that these libraries are included and not Java 8 ones.
import org.threeten.bp.LocalDate
import org.threeten.bp.temporal.ChronoUnit
import org.threeten.bp.temporal.WeekFields
import com.jakewharton.threetenabp.AndroidThreeTen
Code to finish work
var mCurrentTime = LocalDate.now()
val weekFields = WeekFields.of(Locale.GERMANY)
val currentDayOfWeek = mCurrentTime.get(weekFields.dayOfWeek())
//subtract day of week to monday
mCurrentTime=mCurrentTime.minus((currentDayOfWeek.toLong()-1),ChronoUnit.DAYS)
//add week starting from monday
mCurrentTime=mCurrentTime.plus(1,ChronoUnit.WEEKS)
//get weekOfYear
val weekOfCurrentTime=mCurrentTime.get(weekFields.weekOfYear())
show_week_in_year.text=weekOfCurrentTime.toString()
Sorry for Kotlin. Java is on vacation.
Related
I need to convert date (2011-Jan-01) to any of the simpledateformats.
The eclipse designer uses Java 7.
String pDate = obj.getJSONArray("product").getJSONObject(i).getString("createdDate");
//"2011-Jan-01" - date format.
SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
try {
Date fDate = format.parse(pDate);
System.out.println("jsonDate: " + fDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("pDate: " + pDate);//"2011-Jan-01"
errors:
error:java.text.ParseException:Unparseable date:"2011-Jan-01"
error: at java.text.DateFormat.parse(DateFormat.java:348)
I'm getting errors above.
Your parsing format should not include the time (because your input is only the date), and you need another format call to produce your desired output. Something like,
String pDate = "2011-Jan-01";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd");
try {
Date fDate = format.parse(pDate);
System.out.println(new SimpleDateFormat("dd-MM-yyyy").format(fDate));
} catch (ParseException e) {
e.printStackTrace();
}
which outputs
01-01-2011
java.time and ThreeTen Backport
This works on Java 7 (details below):
DateTimeFormatter jsonDateFormatter = DateTimeFormatter.ofPattern("uuuu-MMM-dd", Locale.ENGLISH);
DateTimeFormatter outputDateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
String pDate = "2011-Jan-01";
LocalDate fDate = LocalDate.parse(pDate, jsonDateFormatter);
pDate = fDate.format(outputDateFormatter);
System.out.println("Formatted date: " + pDate);
Output from the snippet is:
Formatted date: 01-01-2011
Unless you have strong reasons not to, I recommend that you use one of Java’s built-in formats for your user’s locale rather than hardcoding an output format. For example:
DateTimeFormatter outputDateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.UK);
Now the output is:
Formatted date: 01-Jan-2011
Question: Why java.time?
The old datetime classes that you tried to use in the question, Date and SimpleDateFormat are poorly designed, the latter notoriously troublesome. Fortunately they are also long outdated. java.time, the modern Java date and time API, is so much nicer to work with.
Question: Can I use java.time on Java 7? How?
Yes, java.time works nicely on Java 7. 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 non-Android 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.
Change SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); to SimpleDateFormat format = new SimpleDateFormat("yyyy-MMM-dd");
I'm trying to localize for Finland using this code:
Locale finLocale = new Locale("fi", "FI");
Date today = new Date(2017, 1, 1);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG, finLocale);
String formattedDate = dateFormat.format(today);
System.out.println(formattedDate);
What I end up getting is "helmikuutata". I would expect "helmikuu" or "helmikuuta", but this just seems wrong.
Is this valid Finnish, or is there a bug in Java? My version is 1.8.0_31
Yes, this was a bug in JDK (See JDK-8074791), wherein an extra 'ta' was appended to the month name. This got fixed from JDK 8u60 version onwards. So, if you upgrade to latest JDK versions like JDK8u131, you will get the correct output.
I am convinced that the answer by Pallavi Sonal is correct. I have already upvoted it and you should probably accept it. I had wanted to keep the following a comment, but it deserves better formatting, so here goes.
java.time
Since you are using Java 8 (and even if you didn’t), you will prefer the modern more programmer friendly API of java.time:
LocalDate today = LocalDate.of(2017, Month.FEBRUARY, 1);
DateTimeFormatter dateFormat = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
.withLocale(finLocale);
String formattedDate = today.format(dateFormat);
On my Java 1.8.0_131 it gives the expected
1. helmikuuta 2017
If someone reading this is using Java 6 or 7, please consider getting the ThreeTen Backport library so you can use the modern date and time API as shown.
I have epoch time and I am trying to get the day of the week. For example lets say I get time as 16/04/2015 16:03:56. I want to find out what day is 16th (Monday, Tuesday... )
scala> import java.text.SimpleDateFormat
import java.text.SimpleDateFormat
scala> import java.util.{TimeZone, Locale}
import java.util.{TimeZone, Locale}
scala> dateFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC"))
scala> val dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.US)
Following code will return time with the date:
scala> dateFormat.format("1429200236824".toLong)
res2: String = 16/04/2015 16:03:56
From this how can I obtain what day is 16th, (above example is in scala but its same is java too)
Java 8 Solution
You should use the new Java 8 DateTime API. It is based on JodaTime and is much nicer to work with. Here is a good overview of the API (http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html).
Using the new API, the following code will get your answer.
Welcome to Scala version 2.11.7 (OpenJDK 64-Bit Server VM, Java 1.8.0_65).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import java.time.ZoneId
import java.time.ZoneId
scala> import java.time.ZonedDateTime
import java.time.ZonedDateTime
scala> import java.time.Instant
import java.time.Instant
scala> ZonedDateTime.ofInstant(Instant.ofEpochMilli("1429200236824".toLong), ZoneId.of("Etc/UTC")).getDayOfWeek
res0: java.time.DayOfWeek = THURSDAY
scala>
Java 7 Standard Library Solution
If you must use Java 7 (you shouldn't use Java 7) then this will get you the day of the week in terms of an Int (1=Sunday, 7=Saturday).
Welcome to Scala version 2.11.7 (OpenJDK 64-Bit Server VM, Java 1.8.0_65).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import java.util.TimeZone
import java.util.TimeZone
scala> import java.util.Calendar
import java.util.Calendar
scala> val c = Calendar.getInstance
c: java.util.Calendar = java.util.GregorianCalendar[time=1445886305100,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Denver",offset=-25200000,dstSavings=3600000,useDaylight=true,transitions=157,lastRule=java.util.SimpleTimeZone[id=America/Denver,offset=-25200000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2015,MONTH=9,WEEK_OF_YEAR=44,WEEK_OF_MONTH=5,DAY_OF_MONTH=26,DAY_OF_YEAR=299,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=5,SECOND=5,MILLISECOND=100,ZONE_OFFSET=-25200000,DST_OFFSET=3600000]
scala> c.setTimeZone(TimeZone.getTimeZone("Etc/UTC"))
scala> c.setTimeInMillis("1429200236824".toLong)
scala> c.get(Calendar.DAY_OF_WEEK)
res2: Int = 5
scala>
Joda-Time
As requested here is a Joda-Time version. Please be aware that the Joda-Time developers are asking you to use the Java 8 Standard Library instead. Once they end of life Joda-Time you will be in danger of using a library that will not get bug fixes, i.e. You should use Java 8.
Welcome to Scala version 2.11.7 (OpenJDK 64-Bit Server VM, Java 1.8.0_65).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import org.joda.time.{DateTimeZone, DateTime}
import org.joda.time.{DateTimeZone, DateTime}
scala> new DateTime("1429200236824".toLong, DateTimeZone.forID("Etc/UTC")).dayOfWeek.getAsText
warning: Class org.joda.convert.FromString not found - continuing with a stub.
warning: Class org.joda.convert.ToString not found - continuing with a stub.
warning: Class org.joda.convert.ToString not found - continuing with a stub.
warning: Class org.joda.convert.FromString not found - continuing with a stub.
warning: Class org.joda.convert.ToString not found - continuing with a stub.
res0: String = Thursday
scala>
I've made a jar for parsing a dateformat from text for JRE and Android.
Mostly It worked well. but when I try to parsing the following Chinese chars, It fails on Android and works on JRE. '五月' is May in Chinese.
"06 五月 2014"
I used the following code to parse it
String input = "06 五月 2014"
SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy", Locale.CHINESE);
Date date = df.parse(input);
So, i started narrowing down the problems and got the following test cases.
on Android,
DateFormatSymbols dfs = new DateFormatSymbols(Locale.CHINA);
String[] months = dfs.getMonths();// months[0] = 1月, months[1] = 2月 ...
String[] ampm = dfs.getAmPmStrings(); // ampm[0] = AM ampm[1] = PM
on JRE 1.7,
DateFormatSymbols dfs = new DateFormatSymbols(Locale.CHINA);
String[] months = dfs.getMonths();// months[0] = 一月, months[1] = 二月 ...
String[] ampm = dfs.getAmPmStrings(); // ampm[0] = 上午 ampm[1] = 下午
Why this happens? is this normal operation or am i missing something ?
Ignoring the difference between Java and Android, your code is not even guaranteed to work on different Java VMs. The API documentation does not cover a formal specification of the different date formatters and you are not guaranteed that the formatted output from one Java VM can be parsed by another Java VM.
In this case, the localization database in the Oracle VM uses "五月" as the Chinese word for the month of May (literary: "fifth moon"). Your Android localization database uses "5月" (literary: "5th moon"), which is just as correct, but different.
I am using Joda time in Java. What package do I need to import to use the following statement?
DateTime now = SystemFactory.getClock().getDateTime();
I'm getting the error "SystemFactory cannot be resolved".
Is that part of the Joda library?
org.phpfirefly.test.joda.factory.SystemFactory
It is not a part of Joda library.
Instead use below line:
private static final DateTime theDateTime = new DateTime(2009, 9, 6, 14, 30, 0, 0);
NOTE:
If you are using an IDE, then it will assist you in importing appropriate packages.