hive equivalent for TD_WEEK_OF_CALENDAR - sql

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;
}

Related

How do you compare selector attributes in Testcafe?

I'm trying to compare the date of videos on a webpage to today's date. If the difference between the two dates is more than X days, report back as false.
The videos on the webpage have a tag in them which uses the format yyyy-mm-dd
I've got a selector set up to find the videos const videoDate = Selector('OPTA-video').withAttribute('data-secondary-time')
Now how do I set a variable to today's date and compare the two? I'm completely stuck!
I was using Katalon Studio before and here's the groovy script that did the same job:
String videoDate = WebUI.getAttribute(findTestObject('OPTA-video'), 'data-secondary_time')
LocalDate todaysDate = LocalDate.now()
LocalDate videoDateParsed = LocalDate.parse(videoDate, dtf)
if (ChronoUnit.DAYS.between(videoDateParsed, todaysDate) > 1) {
KeywordUtil.markFailed('The videos are 2+ days old.')
} else {
KeywordUtil.logInfo('The videos are up to date.')
}
You can use the getAttribute TestCafe method to access an attribute value. Then, parse the attribute value into the JavaScript Date object:
String videoDate = Selector('OPTA-video').getAttribute('data-secondary-time');
Date videoDateParsed = Date.parse(videoDate);
Date todaysDate = Date.now()
...
In the following thread you can find how to compare Date objects.
This is one of the scripts that I am using.
//getting your XPath test value into a string
String ann_time =
WebUI.getText(findTestObject("ObjectRepository/navigateTOElement/announcements_date"))
//converting time to simple date format
SimpleDateFormat sdf = new SimpleDateFormat('HH:mm')
Date sdf_anntime = sdf.parse(new String(ann_time))
//getting Current time
SimpleDateFormat dateFormatGmt = new SimpleDateFormat('HH:mm')
dateFormatGmt.setTimeZone(TimeZone.getTimeZone('GMT'))
SimpleDateFormat dateFormatLocal = new SimpleDateFormat('HH:mm')
currDate = dateFormatLocal.parse(dateFormatGmt.format(new Date()))
// time gap in long format
long duration = currDate.getTime() - sdf_anntime.getTime()
//time gap to mins
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration)
//compare time gap with globale variable
if (diffInMinutes < GlobalVariable.News_updated_time) {
log.logInfo("system is getting updated,last updated "+ diffInMinutes + "min ago")
} else {
CustomKeywords.'errorMessage.logFailed.markStepFailed'('from 1 h, system was not updated')
log.logInfo('from '+ diffInMinutes+ 'h, system was not updated')
}

How to parse DayOfWeek range

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

Get Payment dates in a list

I have a payment check application, in that I get 2 strings:
String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";
Now every payment must be done the last Friday of the month. I need to calculate those dates and place it in a list or array.
Is there any optimal way to do that using the Java 8 nice features?
I started here:
String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";
LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
System.out.println(contractStart);
System.out.println(contractStop);
List<LocalDate> payCheck= new ArrayList<>();
for (int i = 0; i < args.length; i++) {
payCheck.add(...) ??
}
I am not sure about your args array. But If you want to get every last friday of month between the contract start and end date. I would do as follow :
String contractBegin = "01-01-2018";
String contractEnd = "31-12-2018";
LocalDate contractStart = LocalDate.parse(contractBegin, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
LocalDate contractStop = LocalDate.parse(contractEnd, DateTimeFormatter.ofPattern("dd-MM-yyyy"));
List<LocalDate> payCheck = new ArrayList<>();
LocalDate payCheckDate = contractStart;
while (payCheckDate.isBefore(contractStop)) {
payCheckDate = payCheckDate
.with(lastDayOfMonth())
.with(previousOrSame(DayOfWeek.FRIDAY));
payCheck.add(payCheckDate);
payCheckDate = payCheckDate.with(TemporalAdjusters.firstDayOfNextMonth());
}
payCheck.forEach(System.out::println);
This gives you every last friday of each month.
Another alternative to #gnostrenoff's answer is to use TemporalAdjusters.lastInMonth() method, which gives you the specified last day of week in the month:
// get the last Friday of the month
payCheckDate = payCheckDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));
The rest of the while loop is the same as #gnostrenoff's answer.

Siebel Business(E-script) Service Calculate Expiry Date

I have a requirement to create a business service function to calculate expiry date , 2 weeks from a date field in Siebel.
I have written the code in Java which is
public static Date checkexpiry(Date Datefield)
{
Calendar cal = Calendar.getInstance();
cal.setTime(Datefield);
cal.add(Calendar.DATE, -14);
Date twoWeeksToExpiry = cal.getTime();
System.out.println(twoWeeksToExpiry);
return twoWeeksToExpiry;
}
if current date is equal to twoWeeksToExpiry {do .....}
So how can I re-write this code on Siebel using a business service particularly E-script.
The whole idea is have an output Yes is its 2 weeks before a date field in Siebel.
This will later be used in a work flow.
OK so have started Migrating my Java coding skills to Siebel E-Script I came up with this.
function ExpiryNotification(Inputs,Outputs)
{
try
{
var expiryDate = Inputs.GetProperty("DateField");
var eDate= new Date(expiryDate);
var notificationdate = eDate-14;
var currentdate = Today();
if (currentdate==notificationdate){
Outputs.SetProperty("Notification", "Y")
}
else {
Outputs.SetProperty("Notification", "N")
}
catch(e)
{
TheApplication().RaiseErrorText(e.toString());
}
}
However I did not use the Business Service ..I used a calculated field on my Business Component.
The calculated Fields
1 twoWeeksToExpiry = Datefield-14
Notification = IIf (Today()==[twoWeeksToExpiry], "Y", "N")
So this solved the problem without scripting,
Will appreciate any suggestions on my scripting thou I didn't use it.

Difference between datepickers except sundays in infopath

How to get the no of days between two date picker controls in info path except sundays?
If It is possible let me know.
Thanks in advance.........
Using custom code you can do it easily. In this case I'm calculating the number of days (except Sundays) between a given date and today's date.
var navigator = this.MainDataSource.CreateNavigator();
string startDate = navigator.SelectSingleNode("/my:myFields/my:date_start", NamespaceManager).Value;
DateTime startDateTime = DateTime.ParseExact(startDate, "yyyy-MM-dd", null);
DateTime today = DateTime.Today;
int count = 0;
while (startDateTime > today)
{
today = today.AddDays(1);
if (today.DayOfWeek != DayOfWeek.Sunday)
{
count++;
}
}
I hope it helps