void SaveKurByDayAsync(DateTime firstDay , DateTime lastDay)
{
List<DateTime> dateList = new();
for (DateTime date = firstDay; date <= lastDay; date = date.AddDays(1))
{
dateList.Add(date);
}
foreach (DateTime date in dateList)
{
string day = date.Day.ToString();
string year = date.Year.ToString();
string month = date.Month.ToString();
if (int.Parse(month) < 10)
month = "0" + month;
if (int.Parse(day) < 10)
day = "0" + day;
string format = null;
if (date == DateTime.Today)
format = "https://www.tcmb.gov.tr/kurlar/today.xml";
format = "https://www.tcmb.gov.tr/kurlar/" + year + month + "/" + day + month + year + ".xml";
List<XElement> exchangeList = XElement.Load(format).Elements().ToList();
foreach (XElement exchangeItem in exchangeList)
{
Console.WriteLine(decimal.Parse(exchangeItem.Element("ForexBuying").Value, NumberStyles.Number, CultureInfo.InvariantCulture));
}
}
}
I have a method that gets exchange rate information published in xml format every day. But on public holidays xml is not published here and I get NotFound error in 'Load' method. I want to skip that day and move on to the next day, but I couldn't figure it out.
Related
I am looking for a solution about how to get all of my int Parses within one line. At the moment when I start my program I have to enter day, month and year. It is all done line by line. I want a solution or method where this does all of my parsing within one line and within a format of "dd/MM/yyyy".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace date
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("please enter date as dd/MM/yyyy");
int day;
int month;
int year;
day = int.Parse(Console.ReadLine());
month = int.Parse(Console.ReadLine());
year = int.Parse(Console.ReadLine());
Date i = new Date(day, month, year);
Console.WriteLine("{0}/{1}/{2}", i.day, i.month, i.year);
Console.ReadLine();
}
class Date
{
public int month; // 1-12
public int day; // 1-31 depending on month
int value = 1;
public int year
{
get;
private set;
}
public Date(int day, int month, int year)
{
this.day = day;
this.month = month;
this.year = year;
}
public int GetYear()
{
return year;
}
public void SetYear()
{
if (value > 1900 && value <= 2020)
year = value;
else
throw new ArgumentOutOfRangeException("year", value, "out of bounds");
}
private int Month
{
get { return month; }
set
{
if (value > 0 && value <= 12)
month = value;
else
throw new ArgumentOutOfRangeException("Month", value, "Month must be 1-12");
}
}
public int GetDay()
{
return day;
}
public void SetDay()
{
int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (value > 0 && value <= days[month])
day = value;
else if (month == 2 && value == 29 &&
year % 400 == 0 || (year % 4 == 0 && year % 100 != 0))
day = value;
else
throw new ArgumentOutOfRangeException("days", value, "day is out of range");
}
}
}
}
You can use DateTime.Parse/TryParse or DateTime.ParseExact/TryParseExact:
string line = Console.ReadLine();
DateTime dt;
bool validDate = DateTime.TryParseExact(line,"dd/MM/yyyy", DateTimeFormatInfo.InvariantInfo,DateTimeStyles.None, out dt);
if(validDate)
Console.WriteLine(dt.ToLongDateString()); // now correctly initialized
With this format also DateTime.Parse/DateTime.TryParse works:
validDate = DateTime.TryParse(line, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out dt);
I use DateTimeFormatInfo.InvariantInfo to prevent that your local date separator is used instead of /(in case it's different).
Once it is parsed to DateTime it's trivial to create your Date instance:
Date d = new Date(dt.Day, dt.Month, dt.Year);
If you do NOT want to use DateTime.(Try)Parse, you can add a parse method with a Regex in your Date class:
public static Date ParseFromString(string s)
{
//string s = "24/12/2015";
Regex r = new Regex(#"(\d+)[\/](\d+)[\/](\d+)");
Match m = r.Match(s);
if (m.Success)
{
return new Date(m.Groups[1], m.Groups[2], m.Groups[3]);
}
else
{
// throw exception
}
}
You can't parse dd/MM/yyyy formatted string to int because it is not a valid string.
You need to parse it to DateTime first and you can use it's properties to get it's day, month and year as a numbers.
For example;
Console.WriteLine("please enter date as dd/MM/yyyy");
DateTime dt = DateTime.ParseExact(Console.ReadLine(), "dd/MM/yyyy",
CultureInfo.InvariantCulture);
int day = dt.Day;
int month = dt.Month;
int year = dt.Year;
Or you can use TryParseExact if you don't wanna throw exception if input is not dd/MM/yyyy format.
I am not wanting to use the preset DateTime class but I am using my
own "Date" class
If so, after you parse it, you can create your Date class instance with Date(int day, int month, int year) constructor based on this dt value as;
Date myDt = new Date(dt.Day, dt.Month, dt.Year);
for example I have to choose in datetimepicker May 16,2014 the messge box will pop out "This Week" and if I choose in datetimepicker May 20,2014 it will pop out "Next Week" and also June 20,2014 will pop out "Next Month".
I tried this..
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek firstDayOfWeek = ci.DateTimeFormat.FirstDayOfWeek;
int offset = firstDayOfWeek - DateTime.Now.DayOfWeek;
DayOfWeek lastDayOfWeek = DateTime.Now.AddDays(offset).AddDays(6).DayOfWeek;
DateTime nextmonth = DateTime.Now.AddMonths(1);
DateTime input = DateTime.Now.AddDays(1);
input = dateTimePicker1.Value;
DateTime startOfWeek = DateTime.Today;
while (startOfWeek.DayOfWeek != firstDayOfWeek)
startOfWeek = startOfWeek.AddDays(-1);
DateTime endOfWeek = DateTime.Now;
while (endOfWeek.DayOfWeek != lastDayOfWeek)
endOfWeek = endOfWeek.AddDays(1);
bool thisWeek = input >= startOfWeek && input <= endOfWeek;
bool Thismonth = input == startOfWeek && input < endOfWeek;
bool nextMonth = input == nextmonth;
if (thisWeek == true)
{
label1.Text = "This Week";
}
else if (thisWeek == false)
{
label1.Text = "Next Week";
}
else if (nextMonth == true)
{
label1.Text = "Next Month";
}
Not too much of a problem to do. C# provides lots of Date Time Functions, but not "Is this week" although you could write an extension method for this.
System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
DayOfWeek firstDayOfWeek = ci.DateTimeFormat.FirstDayOfWeek;
int offset = firstDayOfWeek - DateTime.Now.DayOfWeek;
DayOfWeek lastDayOfWeek = DateTime.Now.AddDays(offset).AddDays(6).DayOfWeek;
DateTime input = DateTime.Now.AddDays(1);
DateTime startOfWeek = DateTime.Today;
while (startOfWeek.DayOfWeek != firstDayOfWeek)
startOfWeek = startOfWeek.AddDays(-1);
DateTime endOfWeek = DateTime.Now;
while (endOfWeek.DayOfWeek != lastDayOfWeek)
endOfWeek = endOfWeek.AddDays(1);
Console.WriteLine("Week starts: " + startOfWeek);
Console.WriteLine("Week ends: " + endOfWeek);
Console.WriteLine("Input was: " + input);
Console.Write("Is input this week? ");
bool thisWeek = input >= startOfWeek && input <= endOfWeek;
Console.WriteLine(thisWeek);
This is the code I have at the moment:
String getDayRequested;
public void setDay(String getDayFromForm1)
{
getDayRequested = getDayFromForm1;
{
if (getDayRequested.Contains("today"))
{
getDayRequested = DateTime.Today.DayOfWeek.ToString();
}
else if (getDayRequested.Contains("tomorrow"))
{
getDayRequested = DateTime.Today.AddDays(1).DayOfWeek.ToString();
}
}
This checks my TextBox.Text string from Form1, and checks to see if the text "today" or "tomorrow" is in it.
Can anyone help me in the right direction of how to check the string for information asked about upcoming days; ie: "What will be the date this saturday", and add the appropriate number of days depending on what the day is when asked.
UPDATE
Using the code in the accepted answer, I used the following in my above else if statement to complete what I was after:
else if (getDayRequested.Contains("monday"))
{
getDayRequested = GetFutureDay(DateTime.Now, DayOfWeek.Monday).ToString("dd");
}
This handy little method will return a future day of the week.
public DateTime GetFutureDay(DateTime start, DayOfWeek day)
{
int daysToAdd = (day - start.DayOfWeek + 7) % 7;
return start.AddDays(daysToAdd);
}
It would be called like:
var day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), getDayFromForm1);
var getDayRequested = GetFutureDay(DateTime.Now, day);
Consider the following snippet of code...
DateTime date;
public void setDay(String day)
{
DayOfWeek futureDay = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), day);
int futureDayValue = (int)futureDay;
int currentDayValue = (int)DateTime.Now.DayOfWeek;
int dayDiff = futureDayValue - currentDayValue;
if (dayDiff > 0)
{
date = DateTime.Now.AddDays(dayDiff);
}
else
{
date = DateTime.Now.AddDays(dayDiff + 7);
}
}
Good Luck!
I have this:
StringBuilder sb = new StringBuilder(time.Text);
if (DateTime.Parse(time.Text) > DateTime.Parse("12:00:00 AM")
&& DateTime.Parse(time.Text) < DateTime.Parse("11:59:59 AM"))
{
time.Text = time.Text + " AM";
}
else
{
time.Text = time.Text + " PM";
}
What I have now is 16:34 PM,
I want it to display 04:34 PM
Simply
string strTime = DateTime.Now.ToString(#"hh\:mm\:ss tt");
in your case, it will be:
time.Text=DateTime.Parse(time.Text).ToString(#"hh\:mm\:ss tt");
and make sure about custom formats, like HH is 24 hrs format, MM is for month
try
time.Text = DateTime.Parse(time.Text).ToString("hh:mm:ss tt");
public static string FormattedTime(this TimeSpan TimeIn24Hours)
{
String TimeIn12Hours = string.Empty;
if (TimeIn24Hours != null)
{
TimeIn12Hours = DateTime.MinValue.AddHours(TimeIn24Hours.Hours).AddMinutes(TimeIn24Hours.Minutes).ToString("hh:mm");
}
return TimeIn12Hours;
}
private void UpdateTime()
{
int hours, mins, sec;
string TimeofDate = "AM";
currentTime = DateTime.Now;
hours = Convert.ToInt32(currentTime.Hour.ToString());
mins = Convert.ToInt32(currentTime.Minute.ToString());
sec = Convert.ToInt32(currentTime.Second.ToString());
// lbCurrentTime.Text = currentTime.ToLongTimeString();
// label2.Text = hours.ToString() + ":" + mins.ToString() + ":" + sec.ToString();
if (hours >= 12)
{
hours = hours - 12;
TimeofDate = "PM";
}
else TimeofDate = "AM";
lbCurrentTime.Text = hours.ToString() + ":" + mins.ToString() + ":" + sec.ToString()+" "+TimeofDate;
}
I have a small C# program that has a calendar and 7 labels. When I select a date the labels display the days and dates of that week.
The labels are populated using the TimeSpan string what I want to do is format this string so that it only displays the days and dates with out the times.
This is the code I have so far:
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
DateTime dTime = new DateTime();
dTime = monthCalendar1.SelectionStart;
dTime -= new TimeSpan((int)dTime.DayOfWeek, 0, 0, 0 );
for (int i = 1; i < 8; i++)
{
var dt = dTime.AddDays(i);
lb[i].Text = dt.DayOfWeek + " : " + dt.Date;
}
}
You can call dt.Date.ToShortDateString().
You have multiple options.
You can use ToShortDateString() method for the DateTime type
lb[i].Text = dt.DayOfWeek + " : " + dt.Date.ToShortDateString()
or you can provide of a format to the ToString("format") method to specify exactly what you want it to look like.
lb[i].Text = dt.DayOfWeek + " : " + dt.Date.ToString("MM/dd/yyyy");
Try with DateTime.ToShortDateString() method;
Converts the value of the current DateTime object to its equivalent
short date string representation.
DateTime dt = DateTime.Now;
label8.Text = dt.Date.ToShortDateString());
You can learn more details from Custom Date and Time Format Strings