How to obtain first date of each month based on given year range in Nifi flow - apache-nifi

I would like to know what could be the best way to obtain the starting date values for each month based on the date range.
For example: If I am given a year range of 2015-11-10 and 2018-01-15(format YYYY-mm-dd). Then I would like to extract following dates:
2015-12-01
2016-01-01
.
.
2018-01-01

You can try to use this flow for generating the first day of each month in the provided date range.
Overall flow
Step 1 Configuration: Start
Step 2 Configuration: Configure Date Range
Provide the start and end dates as configuration parameters via this step.
Step 3 Configuration: Generate First Dates For Months
This uses a Groovy script, which is provided below
Groovy script
flowFile = session.get();
if(!flowFile)
return;
DATE_FORMAT = 'yyyy-MM-dd';
startDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("start_date"));
endDate = Date.parse(DATE_FORMAT, flowFile.getAttribute("end_date"));
allFirstDates = "";
Calendar calendar = Calendar.getInstance();
Set firstDaysOfMonths = new LinkedHashSet();
for (int i = 0; i <= endDate-startDate; i++) {
calendar.setTime(startDate.plus(i));
calendar.set(Calendar.DAY_OF_MONTH, 1);
firstDayOfMonth = calendar.getTime();
if (firstDayOfMonth.compareTo(startDate) >= 0) {
firstDaysOfMonths.add(calendar.getTime().format(DATE_FORMAT));
}
}
firstDaysOfMonths.each {
firstDayOfMonth -> allFirstDates = allFirstDates + firstDayOfMonth + "\n";
}
flowFile = session.putAttribute(flowFile,"all_first_dates", allFirstDates );
session.transfer(flowFile,REL_SUCCESS)
Step 4 Configuration: View Result
Output of run:
When the flow is run, the attribute all_first_dates will be populated with the first dates of each month in the date range.

Related

Java 8 - SQL Timestamp to Instant with properly formatted time

I've read through the available q and a on SO, but nothing I have found answers my question of how to format my time in 12hour format.
Following is my code that runs a query on a MySQL database and returns results, checking to see if an appointment is within 15 minutes of login so an alert can pop.
public void apptCheck(int userId) throws SQLException {
// this method checks for an appointment occurring within 15 minutes of login
Statement apptStatement = DBQuery.getStatement();
String apptQuery = "Select apt.start, cs.customerName from DBName.appointment apt "
+ "JOIN DBName.customer cs ON cs.customerId = apt.customerId WHERE "
+ "userId = " + userId + " AND start >= NOW() AND start < NOW() + interval 16 minute";
apptStatement.execute(apptQuery);
ResultSet apptRs = apptStatement.getResultSet();
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
apptCheck.setContentText(languageRB.getString("apptSoon") + " " + apptTime.toInstant().atZone(ZoneId.systemDefault()));
apptCheck.showAndWait();
}
My result is:
I want the time to display 3:00, not the 19:00 - 06:00. How can I make that happen?
ZonedDateTime zonedDateTime=ZonedDateTime.of(apptTime.toLocalDateTime(),ZoneId.systemDefault());
You can use ZonedDateTime and format the time as you want.
docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html ZonedDateTime has a lot of features you can see all here and you can get the hour, minute, day etc.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss");
String formattedString = zonedDateTime.format(formatter);
if you only want time in 12hour format you can use this
I found the solution which will perform the UTC to local time conversion and then format the time so that the resulting alert is in 12 hour time format without the date or time zone info. Here is the full code:
while(apptRs.next()) {
Timestamp apptTime = apptRs.getTimestamp("start");
// perform time conversion from UTC to User Local Time
ZoneId zidApptTime = ZoneId.systemDefault();
ZonedDateTime newZDTApptTime = apptTime.toLocalDateTime().atZone(ZoneId.of("UTC"));
ZonedDateTime convertedApptTime = newZDTApptTime.withZoneSameInstant(zidApptTime);
ResourceBundle languageRB = ResourceBundle.getBundle("wgucms/RB", Locale.getDefault());
Alert apptCheck = new Alert(AlertType.INFORMATION);
apptCheck.setHeaderText(null);
// set the Alert text and format in 12 hour format
apptCheck.setContentText(languageRB.getString("apptSoon") +
convertedApptTime.toInstant().atZone(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("h:mm a")) + ".");
apptCheck.showAndWait();
}

How to use date helper in CodeIgniter to find time conflict?

I have a database table
TABLE subject_loads
id (int)
subject_name (varchar)
time_start (time)
time_end (time)
time_diff (decimal)
When I save it on database, it will first check whether the time is not conflicting from the other time already inputed. If it's okay, then compute the time_start and time_end to give me a difference between the two.
Example, 7:30 AM - 8:30 AM is already in database, when i input 8:00 AM - 9:00 AM it will say "conflicting with the other time". Only I can input before 7:30 AM or after 8:30 AM that doesn't overlap from 7:30 AM - 8:30 AM.
Can someone help on how to do this?
First you need to check if overlapping values (compared to new value) already exist. You will do that with:
$query = $this->db->get_where('subject_loads', array('time_start >= ' => $time_start, 'time_end <= ' => $time_end));
if((int)$query->num_rows() > 0)
{
//similar values exist
}
else
{
//you are free to insert values
}
Second part of issue:
$hm1 = "2:12 AM";
$hm2 = "4:41 PM";
$e = conv($hm2) - conv($hm1);
echo $e;
function conv($time)
{
$expl_time = explode(' ', $time);
$t = explode(":", $expl_time[0]);
if ($expl_time[1] == 'PM' || $expl_time[1] == 'pm')
{
$t[0] += 12;
}
return ($t[0] + round($t[1]/60, 1, PHP_ROUND_HALF_UP));
}

Calculate year week number from given period in VBScript

Scenario: Trying to find out the End Week Number(current year's week number) and Start Week Number using a given period. Suppose PeriodWeeks = 10. That means from today's week number to last 10 weeks which surely will go to last year in current situation.
Code I have:
perdiodWeeks = 10 ' this is a constant in the code
periodMonths= periodQtrs * 3 ' this calculates month from given number of quarters
endDate = DateAdd("m",-1,Date)
endYear = DatePart("yyyy", endDate)
endMonth = DatePart("m", endDate)
startDate = DateAdd("m", -(periodMonths-1), endDate)
startYear = DatePart("yyyy", startDate)
startMonth = DatePart("m", startDate)
How can I calculate the following?
startYW ' start year week number
endYW ' end year week number
where value would be endYW = 201506 and startYW = perdiodWeeks from endYW. 06 is the current Week Number of 2015
Calculate the initial date (substract #weeks*7) and use the available functions to retrieve the required information
Option Explicit
Dim periodWeeks
periodWeeks = 10
Dim dateToday, dateStart
dateToday = Now()
dateStart = DateAdd("d",periodWeeks*-7, dateToday)
Dim weekToday, weekStart
weekToday = DatePart("ww",dateToday)
weekStart = DatePart("ww",dateStart)

In windowsphone converting current time into millisecond

i have a time format like this:
string s = DateTime.Now.ToString();
which gives me output like
11/29/2013 6:26:13PM
Now how can i convert this output into millisecond in windowsPhone???
Updated:
First i want to save the current time when the user launch my app. after that whenever the user launch my app again then i also get the time and compare the current launching time with previously stored time and check whether the time difference becomes "one day" or not.
For this comparison i need to covert 11/29/2013 6:26:13PM this into millisecond.
Another question tell me how can i convert "6:26:13PM" only this into millisecond??
If I understood correctly just do this:
Create a date from your input:
DateTime yourInitialDateTime = DateTime.Parse("11/29/2013 6:26:13PM");
After that
TimeSpan span = DateTime.Now - yourInitialDateTime;
So in span.TotalDays you will have how many days has passed.
Edit
If you have only the time of day and want to know the millisecond of that time you must add a date and subtract it with hour 0:00:00 like this:
string dummyDate = "01/01/0001";
DateTime end = DateTime.Parse(dummyDate + " " + "6:26:13PM");
var milli = end.Subtract(new DateTime()).TotalMilliseconds;
That is it.
Try this.
var ThatDay = DateTime.Now.AddDays(-1); //This is hard coded but you have to get from where you are storing.
var Today = DateTime.Now;
var Diff = (Today - ThatDay).Milliseconds;
var FriendlyDiff = (Today - ThatDay).ToFriendlyDisplay(5);
public static class TimeSpanExtensions
{
private enum TimeSpanElement
{
Millisecond,
Second,
Minute,
Hour,
Day
}
public static string ToFriendlyDisplay(this TimeSpan timeSpan, int maxNrOfElements)
{
maxNrOfElements = Math.Max(Math.Min(maxNrOfElements, 5), 1);
var parts = new[]
{
Tuple.Create(TimeSpanElement.Day, timeSpan.Days),
Tuple.Create(TimeSpanElement.Hour, timeSpan.Hours),
Tuple.Create(TimeSpanElement.Minute, timeSpan.Minutes),
Tuple.Create(TimeSpanElement.Second, timeSpan.Seconds),
Tuple.Create(TimeSpanElement.Millisecond, timeSpan.Milliseconds)
}
.SkipWhile(i => i.Item2 <= 0)
.Take(maxNrOfElements);
return string.Join(", ", parts.Select(p => string.Format("{0} {1}{2}", p.Item2, p.Item1, p.Item2 > 1 ? "s" : string.Empty)));
}
}

failed to manipulate my Arraylist

I need help , I have an arrayList of objects . This object contains multiple fields I'm interested in this question by two date fields (date_panne date_mise and running) and two other time fields (heure_panne and time start),
And I would like to obtain the sum of the difference between (date_panne, heure_panne) and (date_mise_en_marche; heure_mise_en_marche) to give the total time of failure.
if someone can help me please I will be gratful this is my function :
public String disponibile() throws Exception {
int nbreArrets = 0;
List<Intervention> allInterventions = interventionDAO.fetchAllIntervention();
List<Intervention> listInterventions = new ArrayList<Intervention>();
for (Intervention currentIntervention : allInterventions) {
if (currentIntervention.getId_machine() == this.intervention.getId_machine()
&& currentIntervention.getDate_panne().compareTo(getProductionStartDate()) >= 0
&& currentIntervention.getDate_panne().compareTo(getProductionEndDate()) <= 0) {
listInterventions.add(currentIntervention);
}
}
savedInterventionList = listInterventions;
return "successView" ;
}
Assuming the the dates are truncated to the day and are of type java.util.Date, and that the times only contain hours, minutes, seconds and milliseconds and are also of type Date, start by creating a method like
private Date combine(Date dateOnly, Date timeOnly) {
Calendar dateCalendar = Calendar.getInstance();
dateCalendar.setTime(dateOnly);
Calendar timeCalendar = Calendar.getInstance();
timeCalendar.setTime(timeOnly);
dateCalendar.add(Calendar.HOUR_OF_DAY, timeCalendar.get(Calendar.HOUR_OF_DAY));
dateCalendar.add(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
dateCalendar.add(Calendar.SECOND, timeCalendar.get(Calendar.SECOND));
dateCalendar.add(Calendar.MILLISECOND, timeCalendar.get(Calendar.MILLISECOND));
return dateCalendar.getTime();
}
Now, it's simply a matter of looping through the interventions you want to sum, computing the difference between the dates as milliseconds, and add them:
long totalMillis = 0L;
for (Intervention intervention : interventions) {
Date marche = combine(intervention.getDateMiseEnMarche(), intervention.getTimeMiseEnMarche());
Date panne = combine(intervention.getDatePanne(), intervention.getTimePanne());
long differenceInMillis = marche.getTime() - panne.getTime();
totalMillis += differenceInMillis;
}

Resources