How To Get Thursdays Of Year Using Carbon - laravel-5.1

I want to get all the Thursdays of a year using Carbon and save it on DB.
so far I could only store the Thursdays of current month. please advice me how to make it for the whole year once.
Current code :
public function getThursdays()
{
return new \DatePeriod(
Carbon::parse("first thursday of this month"),
CarbonInterval::week(),
Carbon::parse("first thursday of next month")
);
}
public function handle()
{
$thursdays = $this->getThursdays();
foreach ($thursdays as $thursday)
{
$Weeks = new Week();
$Weeks->week_starting_date = $thursday;
$Weeks->save();
}
}

You can get the number of weeks per year firstly using WEEKS_PER_YEAR, e.g :
$weeks_per_year = Carbon::WEEKS_PER_YEAR;
After that get the first thursday of year using :
$first_thursday = Carbon::parse("first thursday of this year");
Then loop through all the weeks adding every time one week using Carbon function addWeeks(1) to get the thursday of the next week and so :
for($i=1;$i<$weeks_per_year;$i++)
{
array_push( $thursdays, $first_thursday->addWeeks(1)->toDateString() );
}
FULL code :
$weeks_per_year = Carbon::WEEKS_PER_YEAR;
$first_thursday = Carbon::parse("first thursday of this year");
$thursdays = [$first_thursday->toDateString()];
for($i=1;$i<$weeks_per_year;$i++)
{
array_push( $thursdays, $first_thursday->addWeeks(1)->toDateString() );
}
Output :
An array of all the year thursdays in following format yyyy-mm-dd :
["2016-01-07","2016-01-14","2016-01-21", ... ,"2016-12-29"]
Or you can store dates directely in you DB instead of returning an array like :
for($i=1; $i<$weeks_per_year;$i++){
$Weeks = new Week();
$Weeks->week_starting_date = $first_thursday->addWeeks(1)->toDateString();
$Weeks->save();
}
Hope this helps.

Related

Is it possible to get the high and low of a stock price during the day over a specific timeframe?

Like the title says, is there a way to get the highs and lows of a stock price during the day after a certain time? There's a way to get the days high and low over a period of time:
=GOOGLEFINANCE("AMZN","high","05/01/2020","05/10/2020","DAILY")
=GOOGLEFINANCE("AMZN","low","05/01/2020","05/10/2020","DAILY")
But what about during the day during a specific time period? For example from 9:12AM PST to 11:23AM PST?
Solution#3 : you can use Alpha Vantage by 2 ways, add-on GSheets or a custom function i.e. :
// mike steelson
var apikey = 'xxxxxxxxxxxxxx'
function getAllDataJSONv2(code) {
var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol='+code+'&interval=5min&apikey='+apikey
var data = JSON.parse(UrlFetchApp.fetch(url).getContentText())['Time Series (5min)']
var resultat = []
for (var elem in eval(data)){
resultat.push([elem,eval(data[elem]['1. open']),eval(data[elem]['2. high']),eval(data[elem]['3. low']),eval(data[elem]['4. close']),eval(data[elem]['5. volume'])])
}
return resultat
}
the apikey is free for up to 500 requests a day. https://rapidapi.com/alphavantage/api/alpha-vantage
no, not possible with GOOGLEFINANCE. you can get only the daily value which is usually from 16:00:00
your only other option is to find some website (which doesn't use JavaScript) that holds values you wish for and scrape it into google sheets
Solution1 : You can use Yahoo Finance to retrieve the information you want
function getHistoric(url){
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString).context.dispatcher.stores.HistoricalPriceStore.prices
var result = []
data.forEach(function(elem){
result.push([elem.date,elem.open,elem.high,elem.low,elem.close])
})
return result
}
https://docs.google.com/spreadsheets/d/1Kly5-Vu5jBfrl6xFljdICFJW369X-OCjB22z3Ouzt4Y/copy
Solution#2 : you can build your own data based on yahoo finance https://docs.google.com/spreadsheets/d/1QlqpPkIMjE8_jT6kNME1cLrMmQZ9cSzG-SR2Jjivvqo/edit?usp=sharing
//Mike Steelson
var histo = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('historic')
var code = histo.getRange('B1').getValue()
//put a trigger on historic
function historic(){
if (testDateHour()==true) {histo.appendRow([new Date(),marketPrice(code)])}
}
function marketPrice(code) {
var source = UrlFetchApp.fetch('https://finance.yahoo.com/quote/'+code).getContentText()
var data = JSON.parse(source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}')
return data.context.dispatcher.stores.StreamDataStore.quoteData[code].regularMarketPrice.raw
}
function testDateHour(){
var d = new Date();
// not on sunday and saturday and between 10am and 4pm
if (d.getDay()!=0 && d.getDay()!=6 && d.getHours()>=10 && d.getHours()<=16) {return true}else{return false}
}
Configure your local settings (PST) + update if necessary the period when you want to retrieve the information. Then put the trigger (1min)

How to include lastmonth last week in this months first week using ASP.Net MVC

I wrote a code that brings up Current Month Data and groups it by Week. This is great, but the issue here is that I want to also include Last month's Last weekdays in First Week for This month. The reason being the Current Month date is April 01st, 2021, but I am looking to group data for an entire week.
Here is the example
March Week 4 Starts on 29th March, which falls on Monday
Aprile Week 1 Starts on 01st April, which falls on Thursday.
So, If the Current Month First Week Number of Days is greater than Last Month Last Week Number of Days, how can I group the data in as April First Week which should be from March 29th TO April 04th.
The same shall continue for May, April Last Week has 5 days, and May First week has 2 days. Hence, the grouping should display data for Last Week Aprile and not in First Week May
Action Method
public ActionResult DisplayChart()
{
/*This Month Begin*/
DateTime now = DateTime.Now.AddDays(-3);
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);
/*This Month Ends*/
var result = db.Chats.Where(c => System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) >= startDate &&
System.Data.Entity.DbFunctions.TruncateTime(c.MSTChatCreatedDateTime) <= endDate).Select(x => new {x.MSTChatCreatedDateTime}).ToList().GroupBy(c => new
{
Year = c.MSTChatCreatedDateTime.ToCleanDateTime().Year,
Month = c.MSTChatCreatedDateTime.ToCleanDateTime().Month,
WeekofMonth = c.MSTChatCreatedDateTime.ToCleanDateTime().GetWeekOfMonth()
}).Select(c => new ReportVM
{
Title = string.Format("{0}/{1}/Week{2}", c.Key.Year, c.Key.Month, c.Key.WeekofMonth), //chart x Axis value.
ChatCountCreatdDate = c.Count() //chart y Axis value.
}).ToList();
//return the data to the view.
return View(result);
}
Thank you in advance
try this:
public class MyModel
{
public DateTime? Date { get; set; }
public string GroupBy
{
get
{
if (Date.HasValue)
{
DateTime nowDate = DateTime.UtcNow;
if (nowDate.ToString("dd/MM/yyyy") == Date.Value.ToString("dd/MM/yyyy"))
{
return "Today";
}
else if (nowDate.AddDays(-1).ToString("dd/MM/yyyy") == Date.Value.ToString("dd/MM/yyyy"))
{
return "Yesterday";
}
else if ((nowDate - Date.Value).TotalDays <= 7)
{
return Date.Value.DayOfWeek.ToString();
}
else if ((nowDate - Date.Value).TotalDays <= 14)
{
return "Last Week";
}
else if ((nowDate - Date.Value).TotalDays <= 21)
{
return "Two Weeks Ago";
}
else if ((nowDate - Date.Value).TotalDays <= 28)
{
return "Three Weeks Ago";
}
else if (nowDate.TotalMonths(Date.Value) == 1)
{
return "Last Month";
}
else
{
return "Older";
}
}
return string.Empty;
}
}
}

automatically update label every week

So I was wondering, how could I update a specific label once every week. I have a recipe app and want to present the user with new recipe once a week, i would get the recipe name from an Array
var recipeArray = ["Pasta, Fish, Meatballs"]
var weekNumber = 0
func weeklyRecipe () {
//trigger once a week
if weekNumber <= (recipeArray.count - 1) {
weekNumber += 1
} else {
weekNumber = 0
}
label.text = recipeArray[weekNumber]
}
I have no idea how to work with calendar, and will appreciate any help on the topic.
You can update recipe on any particular day. Suppose you want to update on Sunday. Then
let weekday = Calendar.current.component(.weekday, from: Date())
if weekday == 1 {
// Code for updation
}

Unable to Select the month of a jquery datepicker using the Selenium

I am trying to select a custom date in the datepicker present in the jqueryui.com site, it is able to process the year , but the code that i written for the month is not working.Please find the code that i have used:-
private static void PickDate(WebDriver driver, String day, String mon, String year) throws Exception {
while (year != driver.findElement(By.cssSelector("span.ui-datepicker-year")).getText())
{
if (Integer.parseInt(year) < Integer.parseInt(driver.findElement(By.cssSelector("span.ui-datepicker-year")).getText()))
{
driver.findElement(By.cssSelector("a.ui-datepicker-prev")).click();
System.out.println(driver.findElement(By.cssSelector("span.ui-datepicker-month")).getText());
}
else if (Integer.parseInt(year) > Integer.parseInt(driver.findElement(By.cssSelector("span.ui-datepicker-year")).getText()))
{
driver.findElement(By.cssSelector("a.ui-datepicker-next")).click();
}
}
while (mon != (driver.findElement(By.cssSelector("span.ui-datepicker-month")).getText()))
{
if (driver.findElement(By.cssSelector("span.ui-datepicker-month")).getText() != "January")
{
driver.findElement(By.cssSelector("a.ui-datepicker-prev")).click();
}
if (mon != driver.findElement(By.cssSelector("span.ui-datepicker-month")).getText())
{
driver.findElement(By.cssSelector("a.ui-datepicker-next")).click();
}
}
If the purpose is to select a date in the datepicker, I would rather use execute script than click back and forth. :)
Something like:
((JavascriptExecutor) driver).ExecuteScript("$('#datepicker').datepicker('setDate', new Date(year, month, day))")
If you want to click on the previous/next button, then:
Because your code looks quite complicated, so I would like to provide another approach, which I believe that will be much simpler.
Notice that when you click on the previous/next button, it will move forward/backward by 1 month. So it's better if you firstly calculate how many months in difference between the date you want to select (month and year) and the current shown date on the DatePicker.
If you write in java, you can use something like:
YearMonth selectDate = YearMonth.of(year, month); // year, month are integer
int dp_Year = Integer.parseInt(driver.findElement(By.cssSelector("span.ui-datepicker-year")).getText());
int dp_Month = // convert it yourself
YearMonth dp_Date = YearMonth.of(dp_Year, dp_Month);
int month_diff = dp_Date.until(selectDate, ChronoUnit.MONTHS);
Based on month_diff and its sign (+ or -), you will know which button you need to click on and how many times.
I don't have java to try out, but I hope that the code above will work.

Comparing DOB to date today

I am trying to check the age so I can display a note if the clients are under 23 any idea on how to do so? I am using code first entity framework.
Pretty straight-forward:
var under23 = DateTime.Today.AddYears(-23);
var clients = db.Clients.Where(m => m.ClientDOB > under23);
Essentially, you're just subtracting 23 years from the current date and then querying for clients where DOB is greater than that, i.e. they were born on a date greater than 23 years ago, making them less than 23 years old.
Here is the logic you may use
DateTime date=DateTime.Now;
var expectedMinDate=date.AddYears(-23);
DateTime clientBirthDate=Convert.ToDateTime("23/08/1993");
if(clientBirthDate>expectedMinDate)
{
Console.Write("Smaller than 23");
}
else
{
Console.Write("Greater than or equal to 23");
}
DateTime birthday = new DateTime(1995, 7, 30);
var age = GetAge(birthday);
if (age < 23)
{
// do something
}
public int GetAge(DateTime dob)
{
var today = DateTime.Today;
var age = today.Year - dob.Year;
if (dob > today.AddYears(-age))
age--;
return age;
}

Resources