How to select all the days of the week from a given day? - sql

Given a date I want to get all the other days of that same week, where in the week starts and ends on Saturday and Friday.
Model
public TimeModel
{
public int ID
public DateTime Day
}
What I'm currently doing
public Contrller{
private db = new ModelContext();
public AddDates(DateTime Date)
{
List<Model> list = new List<Model>();
int n = 0;
while(Date.DayofWeek != DayofWeek.Sauturday)
Date = Date.AddDats(-1) // keep subracting the date until I reach Saturday
while(Date.DayofWeek != DayofWeek.Friday
{
list.Add(Find(Date));
//Simply put for each date not Friday
// I find the corresponding model (the one with the same date)
//and add it to the list
Date = Date.AddDays(1)
}
list.Add(Find(Date)); // To add the Friday date to list
}
Note: Not exactly my code, just a simplification of my problem.
To summarize my solution:
a) Subtract given date until Saturday
b) Find model which corresponds to Date
c) Repeat until I reach Friday
d) Add to list once more to include Friday
Is it possible to create a linq/sql statement to simpyly select the needed models (with regards to Date)?

You can find a sample implementation that gets the current week.
List<TimeModel> list = new List<TimeModel>();
int n = 0;
for (int i = 0; i < 200; i++)
list.Add(new TimeModel{ID = i, Day = DateTime.Now.AddDays(-i)});
var currentDay = new TimeModel() {ID = 0, Day = DateTime.Now};
var previousSaturday = currentDay.Day.AddDays(-(int)currentDay.Day.DayOfWeek - 1);
var nextFriday = previousSaturday.AddDays(6);
var currentWeek = list.Where(p => p.Day.DayOfYear >= previousSaturday.DayOfYear && p.Day.DayOfYear <= nextFriday.DayOfYear).OrderBy(p => p.Day.DayOfYear).ToList();

Related

How to calculate date in kotlin with the given format?

How to see if a user can be unbanned or not between 2 dates?
Hi, I have a given variable which is the date the user was unbanned as end_banned in the format HH:mm:ss dd/MM/YYYY.
val end_banned: String= "15:05:00 12/01/2022"
I want to calculate if at the current time they can be unbanned or not. I have tried with SimpleDateFormat, Calendar, Date... but still haven't found a solution.
I've tried separating each element of seconds, minutes, days... and comparing them with if...else like this:
var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var _hours = cal.get(Calendar.HOUR)
var _minutes = cal.get(Calendar.MINUTE)
var _seconds = cal.get(Calendar.SECOND)
var _day = cal.get(Calendar.DAY_OF_MONTH)
var _month = cal.get(Calendar.MONTH) + 1
var _year = cal.get(Calendar.YEAR)
var hours = end_banned.toString().substring(0, 2).toInt()
var minutes = end_banned.toString().substring(3, 5).toInt()
var seconds = end_banned.toString().substring(6, 8).toInt()
var day = end_banned.toString().substring(9, 11).toInt()
var month = end_banned.toString().substring(12, 14).toInt()
var year = end_banned.toString().substring(15).toInt()
if (_year >= year && _month >= month && _day >= day && _hours >= hours && _minutes >= minutes && _seconds >= seconds
|| _year >= year && _month >= month && _day >= day && _hours >= hours && _minutes >= minutes
|| _year >= year && _month >= month && _day >= day && _hours >= hours
|| _year >= year && _month >= month && _day >= day
|| _year >= year && _month >= month
|| _year >= year) {
println("True")
} else {
println("False")
}
But it is only true for the first 3 conditions when there are hours, minutes and seconds.
I tried with SimpleDateFormat and Date like this:
var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var hours = cal.get(Calendar.HOUR)
var minutes = cal.get(Calendar.MINUTE)
var seconds = cal.get(Calendar.SECOND)
var day = cal.get(Calendar.DAY_OF_MONTH)
var month = cal.get(Calendar.MONTH) + 1
var year = cal.get(Calendar.YEAR)
var sdf = SimpleDateFormat("HH:mm:ss dd/MM/yyyy")
var sdf_unbanned = sdf.parse(end_banned)
var sdf_now = sdf.parse("${hours}:${minutes}:${seconds} ${day}/${month}/${year}")
if (sdf_now.time - sdf_unbanned.time <= 0) {
println(true)
} else {
println(false)
}
But this condition always gives an incorrect number if I adjust the now and unbanned variables a few minutes apart (This makes it easier to spot)
I did not fully understand your question Sir, But I assume you want to compare unbanned_date to the current date (now time) if they are the same(we reached the unban date) then it should unban whatever you are unbanning, If so the implementation requires less code to achieve that ,Like this :
val sdf = SimpleDateFormat("dd/MM/yyyy")
val strDate: Date = sdf.parse(end_banned)
if (System.currentTimeMillis() > strDate.getTime()) {
urbanUser = true // or what ever your logic is
}
Shame, I got confused between cal.get(Calendar.HOUR) and cal.get(Calendar.HOUR_OF_DAY)
Because cal.get(Calendar.HOUR) returns only 12h format
And cal.get(Calendar.HOUR_OF_DAY) will return 24h format
I found a workaround and here is the code that I fixed and tested:
var cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("Asia/Ho_Chi_Minh")
var sdf = SimpleDateFormat("HH:mm:ss dd/MM/yyyy")
var hour = cal.get(Calendar.HOUR_OF_DAY)
var minute = cal.get(Calendar.MINUTE)
var second = cal.get(Calendar.SECOND)
var day = cal.get(Calendar.DAY_OF_MONTH)
var month = cal.get(Calendar.MONTH) + 1
var year = cal.get(Calendar.YEAR)
var now: Date? = sdf.parse("${hour}:${minute}:${second} ${day}/${month}/${year}")
var end: Date? = sdf.parse(end_banned)
return now?.time!! > end?.time!!
Thanks for the help.

Calculate number of days excluding sunday in Hive

I have two timestamps as input. I want to calculate the time difference in hours between those timestamps excluding Sundays.
I can get the number of days using datediff function in hive.
I can get the day of a particular date using from_unixtime(unix_timestamp(startdate), 'EEEE').
But I dont know how to relate those functions to achieve my requirement or is there any other easy way to achieve this.
Thanks in Advance.
You can write one custom UDF which takes two columns containing the dates as inputs and counts the difference between the dates excluding sundays.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
public class IsoYearWeek extends UDF {
public LongWritable evaluate(Text dateString,Text dateString1) throws ParseException { //takes the two columns as inputs
SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy");
/* String date1 = "20/07/2016";
String date2 = "28/07/2016";
*/ int count=0;
List<Date> dates = new ArrayList<Date>();
Date startDate = (Date)date.parse(dateString.toString());
Date endDate = (Date)date.parse(dateString1.toString());
long interval = 24*1000 * 60 * 60; // 1 hour in millis
long endTime =endDate.getTime() ; // create your endtime here, possibly using Calendar or Date
long curTime = startDate.getTime();
while (curTime <= endTime) {
dates.add(new Date(curTime));
curTime += interval;
}
for(int i=0;i<dates.size();i++){
Date lDate =(Date)dates.get(i);
if(lDate.getDay()==0){
count+=1; //counts the number of sundays in between
}
}
long days_diff = (endDate.getTime()-startDate.getTime())/(24 * 60 * 60 * 1000)-count; //displays the days difference excluding sundays
return new LongWritable(days_diff);
}
}
Use spark so that It will be more easy to implement and maintain
import org.joda.time.format.DateTimeFormat
def dayDiffWithExcludeWeekendAndHoliday(startDate:String,endDate:String,holidayExclusion:Seq[String]) ={
#transient val datePattern="yyyy-MM-dd"
#transient val dateformatter=DateTimeFormat.forPattern(datePattern)
var numWeekDaysValid=0
var numWeekends=0
var numWeekDaysInValid=0
val holidayExclusionJoda=holidayExclusion.map(dateformatter.parseDateTime(_))
val startDateJoda=dateformatter.parseDateTime(startDate)
var startDateJodaLatest=dateformatter.parseDateTime(startDate)
val endDateJoda=dateformatter.parseDateTime(endDate)
while (startDateJodaLatest.compareTo(endDateJoda) !=0)
{
startDateJodaLatest.getDayOfWeek match {
case value if value >5 => numWeekends=numWeekends+1
case value if value <= 5 => holidayExclusionJoda.contains(startDateJodaLatest) match {case value if value == true => numWeekDaysInValid=numWeekDaysInValid+1 case value if value == false => numWeekDaysValid=numWeekDaysValid+1 }
}
startDateJodaLatest = startDateJodaLatest.plusDays(1)
}
Array(numWeekDaysValid,numWeekends,numWeekDaysInValid)
}
spark.udf.register("dayDiffWithExcludeWeekendAndHoliday",dayDiffWithExcludeWeekendAndHoliday(_:String,_:String,_:Seq[String]))
case class tmpDateInfo(startDate:String,endDate:String,holidayExclusion:Array[String])
case class tmpDateInfoFull(startDate:String,endDate:String,holidayExclusion:Array[String],numWeekDaysValid:Int,numWeekends:Int,numWeekDaysInValid:Int)
def dayDiffWithExcludeWeekendAndHolidayCase(tmpInfo:tmpDateInfo) ={
#transient val datePattern="yyyy-MM-dd"
#transient val dateformatter=DateTimeFormat.forPattern(datePattern)
var numWeekDaysValid=0
var numWeekends=0
var numWeekDaysInValid=0
val holidayExclusionJoda=tmpInfo.holidayExclusion.map(dateformatter.parseDateTime(_))
val startDateJoda=dateformatter.parseDateTime(tmpInfo.startDate)
var startDateJodaLatest=dateformatter.parseDateTime(tmpInfo.startDate)
val endDateJoda=dateformatter.parseDateTime(tmpInfo.endDate)
while (startDateJodaLatest.compareTo(endDateJoda) !=0)
{
startDateJodaLatest.getDayOfWeek match {
case value if value >5 => numWeekends=numWeekends+1
case value if value <= 5 => holidayExclusionJoda.contains(startDateJodaLatest) match {case value if value == true => numWeekDaysInValid=numWeekDaysInValid+1 case value if value == false => numWeekDaysValid=numWeekDaysValid+1 }
}
startDateJodaLatest = startDateJodaLatest.plusDays(1)
}
tmpDateInfoFull(tmpInfo.startDate,tmpInfo.endDate,tmpInfo.holidayExclusion,numWeekDaysValid,numWeekends,numWeekDaysInValid)
}
//df way 1
val tmpDF=Seq(("2020-05-03","2020-06-08",List("2020-05-08","2020-06-05"))).toDF("startDate","endDate","holidayExclusion").select(col("startDate").cast(StringType),col("endDate").cast(StringType),col("holidayExclusion"))
tmpDF.as[tmpDateInfo].map(dayDiffWithExcludeWeekendAndHolidayCase).show(false)
//df way 2
tmpDF.selectExpr("*","dayDiffWithExcludeWeekendAndHoliday(cast(startDate as string),cast(endDate as string),cast(holidayExclusion as array<string>)) as resultDays").selectExpr("startDate","endDate","holidayExclusion","resultDays[0] as numWeekDaysValid","resultDays[1] as numWeekends","resultDays[2] as numWeekDaysInValid").show(false)
tmpDF.selectExpr("*","dayDiffWithExcludeWeekendAndHoliday(cast(startDate as string),cast(endDate as string),cast(holidayExclusion as array<string>)) as resultDays").selectExpr("startDate","endDate","holidayExclusion","resultDays[0] as numWeekDaysValid","resultDays[1] as numWeekends","resultDays[2] as numWeekDaysInValid").show(false)
// spark sql way, works with hive table when configured in hive metastore
tmpDF.createOrReplaceTempView("tmpTable")
spark.sql("select startDate,endDate,holidayExclusion,dayDiffWithExcludeWeekendAndHoliday(startDate,endDate,holidayExclusion) from tmpTable").show(false)

asp.net mvc , raw sql : Display data in Views generated using aggregate function

I am using ASP.NET MVC, EF 6 and SQL Server 2008.
I want to generate a view which would show sum of all the sales in each day for a particular month in a particular year.
I found LINQ query very complicated in such type of job, So I used a raw SQL query. I wrote query and tested in SQL server and it worked fine.
select
YEAR(Date) as Year,
MONTH(Date) as month,
DAY(Date) as date,
SUM(GrandTotal) as Total
from
Sales
where
Year(Date) = 2014
and MONTH(Date) = 12
group by
DAY(Date), YEAR(Date), MONTH(date)
Result
Well currently I don't have much data. But it looks like I got what I wanted from a query.
I wrote a controller for this purpose and now I have no idea how to display this data in View.
public ActionResult MonthlySalesByDate()
{
DateTime today = DateTime.Now.Date;
int _year = today.Year;
int _month = today.Month;
//raw sql query
string query = "select SUM(GrandTotal) as Total, DAY(Date) as date, MONTH(Date) as month, YEAR(Date) as Year from Sales where Year(Date) = " + _year + " and MONTH(Date) =" + _month + " Group by DAY(Date), YEAR(Date), MONTH(date)";
//executing raw sql query
var _model = db.Stocks.SqlQuery(query).ToList();
return View(_model);
}
Please help me out with this. If there is better way of doing this or if I am making mistakes, please let me know.
Start by creating view models to represent what you want to display in the view
public class DayTotalVM
{
public int Day { get; set; }
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Total { get; set; }
}
public class SalesVM
{
[DisplayFormat(DataFormatString = "{0:MMMM yyyy}")]
public DateTime Date { get; set; }
public List<DayTotalVM> Days { get; set; }
}
The sql query you have can be generated in linq and projected into your view models using
int year = 2014;
int month = 12;
var query = db.Sales.Where(x => x.Date.Year == year && x.Date.Month == month)
.GroupBy(x => x.Date).Select(g => new DayTotalVM
{
Day = g.Key.Day,
Total = g.Sum(x => x.Total)
})
However this will only give you the 2 items as per you above image, but from the comments you want to display all days in the month, so you can add
int daysInMonth = DateTime.DaysInMonth(year, month);
List<DayTotalVM> days = new List<DayTotalVM>();
for(int i = 1; i < daysInMonth + 1; i++)
{
DayTotalVM item = new DayTotalVM () { Day = i };
DayTotalVM ex = query.Where(x => x.Day == i).FirstOrDefault();
if (ex != null)
{
item.Total = ex.Total;
}
days.Add(item);
}
and finally initialize and return your view model
SalesVM model = new SalesVM();
{
Date = new DateTime(year, month, 1),
Days = days
}
return View(model);
And then the view would be
#model SalesVM
#Html.DisplayFor(m => m.Date);
<table>
#for(int i = 0; i < Model.Days.Count; i++)
{
<tr>
<td>#Html.DisplayFor(m => m.Days[i].Day)</td>
<td>#Html.DisplayFor(m => m.Days[i].Total)</td>
</tr>
}
</table>
Edit
The for loop could be replace by using a GroupJoin()
public ActionResult MonthlySalesByDate(int year, int month)
{
int daysInMonth = DateTime.DaysInMonth(year, month);
var days = Enumerable.Range(1, daysInMonth);
var query = db.Sales.Where(x => x.Date.Year == year && x.Date.Month == month).Select(g => new
{
Day = g.Date.Day,
Total = g.Total
});
var model = new SalesVM
{
Date = new DateTime(year, month, 1),
Days = days.GroupJoin(query, d => d, q => q.Day, (d, q) => new DayTotalVM
{
Day = d,
Total = q.Sum(x => x.Total)
}).ToList()
};
return View(model);
}

MpAndroidChart CandleStick Showing a range with dual seekbar?

I am using a dual seekbar to select the min and max range.
It works when taking the max range down, but when pulling the min range up it fails.
The range seekbar OnRangeSekkbarChangedListener:
RangeSeekBar.OnRangeSeekBarChangeListener<Integer> skListener = new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
int max = bar.getSelectedMaxValue().intValue();
int min = bar.getSelectedMinValue().intValue();
mChart.resetTracking();
//Hold of actual drawing lists
List<CandleEntry> y = new ArrayList<CandleEntry>();
List<String> x = new ArrayList<String>();
for (int i = min; i < max ; i++){
//get candle entry from
CandleEntry current = yVals.get(i);
String currentDate = xVals.get(i);
y.add(current);
x.add(currentDate);
}
//Show less of the chart and invalidate
CandleDataSet mSet = new CandleDataSet(y, "Price");
mSet.setDecreasingColor(getResources().getColor(R.color.black));
mSet.setIncreasingPaintStyle(Paint.Style.FILL);
mSet.setIncreasingColor(getResources().getColor(R.color.accent));
mSet.setDecreasingPaintStyle(Paint.Style.FILL);
mSet.setShadowColor(getResources().getColor(R.color.black));
mCandledata = new CandleData(x, mSet);
//Don't show value text
mCandledata.setDrawValues(false);
mChart.setData(mCandledata);
mChart.invalidate();
}
};
rangeSeekBar.setOnRangeSeekBarChangeListener(skListener);
Results Sceenshots:
Initial Load:
Max Range pulled to near beginning:
Min Range pulled to near end:
You need to change the xIndex of the candle Entries. The first candle needs to have an xIndex of 0
int xIndex = 0;
for (int i = min; i < max ; i++){
//get candle entry from
CandleEntry current = yVals.get(i);
String currentDate = xVals.get(i);
//set the xIndex value
x.setXIndex(xIndex);
y.add(current);
x.add(currentDate);
xIndex++;
}

How do i create a calculated measure that will filter data by days overdue

I have a field in my fact table called days overdue. I would like to create a set that will do the following: If the days due is between 0 - 29, then 0 - 29 days overdue, if between 30 and 59 days old, then '30 - 59 days overdue. How would i create this?
We need to know what kind of array you're using, or linked list, or my favorite for these things, a vector, etc.
If you were using a vector, you would create your own class to be used as a datatype with things like:
Class MyData
{
String name;
int daysPastDue; // how you want to factor this is up to you,
// i suggest looking into Java.util.date or Java.util.calendar
public MyData
{
name = "";
daysPastDue = 0;
}
}
Class DoWork
{
public void myWork() // excuse the indent, forgot to put in the class name
{
vector <MyData> input;
MyData 0To29 [] = new MyData[input.size()];
MyData 33To59 [] = new MyData[input.size()];
MyData item = new MyData();
int 0To29count = 0;
int 30To59count = 0;
for (i = 0; i <= list.size(); i++)
{
item = input.elementAt(i)
if (item.daysPastDue <= 29)
{
0To29[0To29Count] = input;
0To29Count ++;
}
elseif (item.daysPastDue >= 30 && item.daysPastDue <= 59)
{
30To59[30To59Count] = input;
30To59Count ++;
}
}
}
}
then you have your 2 arrays and can output them as you wish. however i would recommend starting at daysPastDue = 100000 and decrement it and check the number through the vector until you have all the items in the vector listed. That way they're all in order from the most past due, to the least and you get the output of exactly how long they've been past due.