As part of an opening times page, I want to parse a DayOfWeek range as (Monday to Friday) rather than creating a String for every day of the working week. Is there a way that this can be done so that the default locale automatically changes the range? I also expect TalkBack to say the text in Desired output when it is selected.
Desired output
English: Monday to Friday
English (US): Monday through Friday
French: du lundi au vendredi
Japanese: 月曜日から金曜日まで
Current code
String dayMonday = DayOfWeek.MONDAY.getDisplayName(TextStyle.FULL, Locale.getDefault())
String dayFriday = DayOfWeek.FRIDAY.getDisplayName(TextStyle.FULL, Locale.getDefault())
myTv.text = dayMonday + dayFriday
Current result
MondayFriday
Horribly belated answer, but to detail the point I was trying to get across in my comment.
Having language files for this which specify the structure of the phrase, as well as another one for the days of the week.
For example, you could have your phrasing files like:
phrasing.properties:
phrasing.dayrange=%1$s to %2$s
phrasing_en_US.properties:
phrasing.dayrange=%1$s through %2$s
phrasing_fr_FR.properties:
phrasing.dayrange=du %1$s au %2$s
Note there is no requirement for spaces before/after the %n$s points. String.format (which will eventually be used, see below) has no such restriction.
And then have your day-name files as:
daynames.properties:
dayname.monday=Monday
dayname.tuesday=Tuesday
...
daynames_fr_FR.properties:
dayname.monday=Lundi
dayname.tuesday=Mardi
And then in your code you do something like:
/**
* Expects {#code fromDay} and {#code toDay} to be
* {#code Strings} in the format {#literal "monday"},
* {#literal "tuesday"}, etc. <emph>in English</emph>.
*/
public String formTheString(final String fromDay,
final String toDay) {
final ResourceBundle phrasingBundle = ResourceBundle.get("phrasing");
// Get the phrasing format: '%1$s ...' style
final String phrasing = phrasingBundle.getString("dayrange");
final ResourceBundle dayNameBundle = ResourceBundle.get("daynames");
// Get the translated day names
final String localisedFromDay = dayNameBundle.getString(fromDay);
final String localisedToDay = dayNameBundle.getString(toDay);
// Use the 'phrasing' as a format, passing in
// the translated day names as the parameters
// to it.
return String.format(phrasing, localisedFromDay, localisedToDay);
}
Alternatively to the 'dayname' files, you can do what the other answer here suggested.
This may help you. This gets a calander, sets it to the first day of the week.
Then, creates a formatter that outputs the day name, for a particular Locale - in this case France, but you can change it to what you like.
Finally, it prints out the day name, adds 5 days, then prints out the dayname again.
public static void main(String arg[]) {
GregorianCalendar cal = new GregorianCalendar();
cal.set(cal.DAY_OF_WEEK,cal.getFirstDayOfWeek());
SimpleDateFormat sdf = new SimpleDateFormat("EEEEEEEEEE", Locale.FRANCE);
System.out.println(sdf.format(cal.getTime()));
cal.add(cal.DAY_OF_WEEK, 5);
System.out.println(sdf.format(cal.getTime()));
}
For this example, I get the output:
lundi
samedi
Related
I am new to this code.
While running automation script, the date is automatically picked todays date.
actually the date starts from 01/01/2022.
How to change this code?
public void validateStartDateDefaultValueNew() throws Exception{
Date date = Calendar.getInstance().getTime();
DateFormat date formatter = new SimpleDateFormat( pattern: "dd/MM/yyyy");
String today = dateformatter.format(date);
System.out.println("today is "+today);
System.out.println("formatted today is "+date formatter.parse(today))
String [] actual1 = searchStartDateInput.getAttribute("value").split(regor " ");
String actual actuall[0]; =
System.out.println("today actual app is [+actual);
Assert.assertEquals(today, actual);
In your code, you mentioned -
'Date date = Calendar.getInstance().getTime();'.
This line of code takes today's date and current time.
If you want the start date to be '01/01/2022', then hard-code it in your code.
My mobile timezone was GMT+7, I have a code to convert a specific date time(GMT+0) to a specific timezone(GMT+3):
var strDate = "2020-07-10 04:00:00+0000"
var result: Date?
var dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ")
dateFormatter.timeZone = TimeZone.getTimeZone("Asia/Jerusalem")
result = dateFormatter.parse(strDate)
The problem is result always return "Fri Jul 10 11:00:00 GMT+07:00 2020"
But I expected it will return date object "Fri Jul 10 07:00:00 GMT+03:00 2020", any idea what's wrong with my code?
It's recommended to use java.time and stop using java.util.Date, java.util.Calendar along with java.text.SimpleDateFormat because of problems like this one.
In your code, the target time zone is obviously not applied to the date but it isn't obvious why it isn't.
A different problem might be pattern you are using because your example String does not contain any unit of time smaller than seconds but the pattern tries to consider .SSS (which made the code fail in the Kotlin Playground).
Switch to java.time and handle this with modern classes, such as OffsetDateTime for parsing this String (it doesn't contain information about a specific time zone, just an offset of zero hours) and ZonedDateTime as the target object (this considers a real time zone which may have different offsets depending things like Daylight Saving Time).
You could do it like this:
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
fun main() {
// this example is in UTC (+0000 --> no offset / offset of 0 hours)
var strDate = "2020-07-10 04:00:00+0000"
// create a formatter that can parse Strings of this pattern
// ([] represents optional units to be parsed)
var dateFormatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss[.SSS]Z")
// and parse the String to an OffsetDateTime using this formatter
var resultOfParsing = OffsetDateTime.parse(strDate, dateFormatter)
// then print the parsed result
println(resultOfParsing)
// create the target time zone
var timeZone = ZoneId.of("Asia/Jerusalem")
// then use the target zone for a zone shift
var jerusalemTime: ZonedDateTime = resultOfParsing.atZoneSameInstant(timeZone)
// and print the result
println(jerusalemTime)
// you could use your formatter defined above for a differently formatted output, too
println(jerusalemTime.format(dateFormatter))
}
which outputs (including all intermediate results):
2020-07-10T04:00Z
2020-07-10T07:00+03:00[Asia/Jerusalem]
2020-07-10 07:00:00.000+0300
I am trying to implement a query already written for Teradata in Hive and was using weekofyear() until now as a replacement of TD_WEEK_OF_CALENDAR method which returns an INTEGER value representing the number of full weeks since and including the week of 01/01/1900, where the first partial week is 0.
I couldn't find any other predefined UDF in Hive related to this method. Even for writing a custom UDF in Java, I was not able to get the exact logic of TD_WEEK_OF_CALENDAR.
Can someone please help on this?
This can be achieved using the Joda time functions. But Hive doesn't support Joda time Jars and you need to explicitly add the joda-time jars to your hive lib folder.
The function TD_WEEK_OF_CALENDAR treats Sunday as first day of week and Saturday as last whereas the joda-time function getDayOfWeek() treats Sunday as last day of the week giving its number as 7 which pulls Sunday into the same week.
This below code would to the needful
public Text evaluate(Text input) {
if(null != input){
String date = input.toString();
StringTokenizer st = new StringTokenizer(date, "-");
int year = Integer.parseInt(st.nextToken());
int month = Integer.parseInt(st.nextToken());
int day = Integer.parseInt(st.nextToken());
DateTime dateTime1 = new DateTime(1900, 1, 1, 0, 0, 0, 0);
DateTime dateTime2 = new DateTime(year, month, day, 0, 0, 0, 0);
int weeksDiff = dateTime2.getDayOfWeek() == 7 ? Weeks.weeksBetween(
dateTime1, dateTime2).getWeeks() + 1 : Weeks.weeksBetween(
dateTime1, dateTime2).getWeeks();
String weeks = weeksDiff + "";
return new Text(weeks);
} else {
return null;
}
I have WSDL as follows:
< xsd:simpleType name="USER_ACT_STRDT_TypeDef">
< xsd:annotation>
< xsd:documentation>USER_ACT_STRDT is a date.< /xsd:documentation>
< /xsd:annotation>
< xsd:restriction base="xsd:date">
< xsd:pattern value="(\d{4}-\d{2}-\d{2})"/>
< /xsd:restriction>
< /xsd:simpleType>
When I generate the STUB (using Axis2 1.5.3), the generated stub (ADB Data Binding) has the following source code :
public void setUSER_ACT_STRDT_TypeDef(Date param) {
if (ConverterUtil.convertToString(param).matches("\d{4}-\d{2}-\d{2}")) {
this.localUSER_ACT_STRDT_TypeDef=param; } else { throw new java.lang.RuntimeException();
} }
This method always throws RuntimeException because the ConverterUtil.convertToString() method returns a String in a different format than "yyyy-mm-dd". It returns the date by appending +5.30 as 2011-03-21+05:30.
I tried passing the date in different formats but same result for all.
Can any one suggest how to resolve this issue.
This code:
if (ConverterUtil.convertToString(param).matches("\\d{4}-\\d{2}-\\d{2}"))
will work only with one of date representations available. In WSDL date specification you will find that 2011-03-21+05:30 is also correct date representation, it simply include time zone as +5 hours and 30 minutes offset to UTC.
Axis2 by default generate dates with timezone but should be able to operate on other date formats.
To check if string starts with YYYY-MM-DD date you can use such code:
if (! sd.matches("\\d{4}-\\d{2}-\\d{2}.*"))
throw new ParseException("Something is terribly wrong with date: " + sd, 0);
else
{
sd = sd.substring(0, 10);
System.out.println("ok: '" + sd + "'");
}
PS Do you escape \d as \\d?
PPS Why do you throw RuntimeException? There are much "better" exceptions like ParseException (used by JDK date parsing methods) or IllegalArgumentException (used by joda time library)
i have a remote sql satabase, and i connect him by php with JSON.
I can get string and int data OK, but now i have a problem.... i have a datetime field on my SQL database, and i dont know how to get it with JSON into java.util.Date
this is the code i tryed, but it fails getting the Date correctly, it gives me an exception (java.lang.ClassCastException: java.lang.String)
code:
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
positions.add(new Position(json_data.getString("latitude"), json_data.getString("longitude"), (Date)json_data.get("timestamp")));
}
You will have to fetch the string sent in the JSON data and parse that string with something like SimpleDateFormat.
In my projects I have used two different solutions.
Storing the Date not as Date but as long(milisecs since 1.1.1980). In Java you can get this with date.getTime(). There should also a methode in PHP. The get the Date Object in Java just pass the long value to the constructor(date= new Date(long_value)).
With this Method you may have problems when dates comes from different time zones.
Write the Date as a formatted Date String in the JSON. How you encode the Date is up to you. A short sample give below. see[1] for further infos.
To get the Date you need a SimpleDateFormater.
DateFormat df = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
try
{
Date today = df.parse("2001.07.04 AD at 12:08:56 PDT");
System.out.println("Today = " + df.format(today));
}
catch (ParseException e)
{
e.printStackTrace();
}
[1]http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html