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
Related
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.
This will be a noobish question but I am currently working on a program that will take in a user input in the format of DD/MM/YYYY and the output it in the format 1st of May 2017, for example.
But whenever the use string.substring (UserInput.substring in my case) it does not separate the values correctly. For example, when I input the date as 21/05/2001 it displays 215 2001. I have no idea why this is happening.
Im sorry as this is very noobish but I am new to using .substring and I'm sure the problem will seem obvious when someone points it out xD
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DateProgram
{
class Program
{
static void Main(string[] args)
{
/// Define Varibles
string UserIntput;
int Day;
int Month;
int year;
///Gathering UserInput
Console.Write("Please enter the date in the format dd/mm/yyyy");
UserIntput = Console.ReadLine();
///Validations
try
{
while(UserIntput.Substring(2,1) != "/" || UserIntput.Substring(5,1) != "/" || UserIntput.Length != 10)
{
Console.WriteLine("Invalid Input");
Console.Write("Please enter the date in the format dd/mm/yyyy");
UserIntput = Console.ReadLine();
}
}
catch
{
Console.WriteLine("Invalid Input");
}
/// Defining to Variables
Day = Convert.ToInt32(UserIntput.Substring(0, 2));
Month = Convert.ToInt32(UserIntput.Substring(3, 2));
year = Convert.ToInt32(UserIntput.Substring(6, 4));
Console.WriteLine(Day + "" + Month + " " + year);
Console.ReadLine();
}
}
}
Pass your user input string in to a System.Convert.ToDateTime method:
DateTime dt = Convert.ToDateTime(UserIntput);
Then, if you would like to change the format of how it is presented, use one of the DateTime.ToString() overloads to convert it to the format you want. (Search for ToString() on this page)
It might look something like this:
dt.ToString("MM-dd-yyyy", System.Globalization.CultureInfo.InvariantCulture);
You'll also want to review this page: Custom Date and Time Format Strings
Use ParseExact like this:
using System;
public class Program
{
public static void Main()
{
DateTime? dt = null;
do
{
Console.WriteLine("Input date: (dd/MM/yyyy)");
var input = Console.ReadLine();
try
{
dt = DateTime.ParseExact(input, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
} while (!dt.HasValue);
Console.WriteLine(dt.Value.ToString("F"));
var myDate = dt.Value;
// access the single fields from the parsed object
Console.WriteLine(myDate.Day);
Console.WriteLine(myDate.Month);
Console.WriteLine(myDate.DayOfWeek);
Console.WriteLine(myDate.Year);
}
}
See https://dotnetfiddle.net/TeYSF7
In addition to the "custom" link for DateTime-Formatting (see BobbyA's answer), consider these which come by default: standard-date-and-time-format-strings
Using string.Split(..) - although why if DateTime comes with valid ways to parse.
var parts = "22/12/2012".Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 3)
{
var day = int.Parse(parts[0]); // will crash if not an int - use .TryParse(...) or handle error
var month = int.Parse(parts[1]); // will crash if not an int
var year = int.Parse(parts[2]); // will crash if not an int
var date = new DateTime(day,month,year)) // will crash if f.e. 45.24.788
}
else
{
// invalid input
}
Try parsing date and time with a help of DateTime.TryParseExact which has been specially designed for such tasks:
using System.Globalization;
...
DateTime userDate;
// Gathering UserInput (just one simple loop)
do {
Console.WriteLine("Please enter the date in the format dd/mm/yyyy");
}
while (!DateTime.TryParseExact(Console.ReadLine(),
"d/m/yyyy", // be nice, let 21.5.2017 be valid; please, do not inist on 21.05.2017
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal,
out userDate));
// If you insist on these local variables:
int day = userDate.Day;
int month = userDate.Month;
int year = userDate.Year;
// But I suggest formatting or string interpolation:
Console.WriteLine($"{userDate:dd MM yyyy}");
Assuming you want to keep your current approach (instead of using any of the built-in functions provided in the other answers), your problem is just a typo.
Change this:
Console.WriteLine(Day + "" + Month + " " + year);
To this:
Console.WriteLine(Day + " " + Month + " " + year); //Notice the space
In the future, you can avoid this sort of problem by using a constant:
const string space = " ";
Console.WriteLine(Day + space + Month + space + year);
I have a for loop in date time how ever counter doesn't increase. I didn't see the reason. Can you help me on it?
private void ubGO_Click(object sender, EventArgs e)
{
DateTime startDate = udteMin.DateTime.Date;
DateTime endDate = udteMax.DateTime.Date;
for (DateTime counter = startDate; counter <= endDate; counter.AddDays(1))
{
MessageBox.Show(counter.Date.ToString() + " " + counter.AddDays(1).Date.ToString());
}
}
AddDays returns a new DateTime object. It doesn't mutate your existing one. You'll need to reassign counter with the result of AddDays
counter = counter.AddDays(1);
This question already has answers here:
date difference using datepicker in wpf
(2 answers)
Closed 8 years ago.
I want to calculate the differences between two dates, one picked form dateTimePicker1 and the other one 20 February of 2014 and store it in a string to added to my array and be able to display it in another form
THIS is my code:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
int differenceInDays = ts.Days;
string differenceAsString = differenceInDays.ToString();
return ts;
}
public class Patient
{
public string patientidString;
public string firstNameString;
public string lastNameString;
public string dateString;
public string differenceAsString;
public Patient()
{
patientidString = "";
firstNameString = "";
lastNameString = "";
dateString = "";
}
}
//Array
Patient[] patientInfo = new Patient[10];
private void button1_Click(object sender, EventArgs e)
{
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker1.Value);
if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0 || textBox3.Text.Length == 0)
{
MessageBox.Show(" Patient id, first name and last name cannot be empty");
}
else
try
{
foreach (Patient patientinfoIndex in patientInfo)
patientInfo[itemCountInteger].patientidString = textBox1.Text;
patientInfo[itemCountInteger].firstNameString = textBox2.Text;
patientInfo[itemCountInteger].lastNameString = textBox3.Text;
patientInfo[itemCountInteger].dateString = dateTimePicker1.Text;
string names = patientInfo[itemCountInteger].patientidString + " " + patientInfo[itemCountInteger].firstNameString + " " + patientInfo[itemCountInteger].lastNameString;
listBox1.Items.Add(names);
itemCountInteger++;
listBox1.SelectedItem = names;
}
catch
{
MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
}
}
//Search Button search a patients name and display his surname in the label if patient is found display his surname
private void button2_Click(object sender, EventArgs e)
{
int intTest = 0;
for (int x = 0; x < patientInfo.Length; x++)
{
if (textBox4.Text == patientInfo[x].patientidString)
{
label6.Text = (patientInfo[x].firstNameString + " " + patientInfo[x].lastNameString);
PatientForm patientform = new PatientForm();
patientform.Show();
patientform.label6.Text = (patientInfo[x].patientidString);
patientform.label7.Text = (patientInfo[x].firstNameString);
patientform.label8.Text =(patientInfo[x].lastNameString);
patientform.dateTimePicker1.Text = (patientInfo[x].dateString);
patientform.label9.Text = (patientInfo[x].differenceAsString);
intTest = 1;
break;
}
}
if (intTest == 0)
{
label6.Text = ("not found");
}
}
DateTime febDate = new DateTime(2014, 2, 20);
DateTime pickerDate = myDateTimePicker.Value;
TimeSpan tspan = febDate - pickerDate;
int differenceInDays = tspan.Days;
string differenceAsString = differenceInDays.ToString();
If differenceInDays < 0 then multiply it by -1.
Note: In this case it's very easy to get the difference in hours, minutes or seconds as well.
Here's an example of the above code in it's own method:
TimeSpan getDateDifference(DateTime date1, DateTime date2)
{
TimeSpan ts = date1 - date2;
return ts;
}
And when you want to trigger this method:
TimeSpan difference = getDateDifference(new DateTime(2014, 2, 20), dateTimePicker.Value);
//Now you can do what you want with the TimeSpan.
int differenceInDays = difference.Days;
int differenceInHours = difference.Hours;
Console.WriteLine(differenceInDays.ToString());
DateTime a = new DateTime.Parse(string);
Console.WriteLine(datePicker.Value.Subtract(a).TotalMinutes);
You can subtract any two dates and it will work.
DateTime date1 = new DateTime(2014,02,20);
DateTime date2 = dateTimePicker1.Value as DateTime;
TimeSpan difference = date1 - date2; //dunno what difference you need so you can swap these
Hi I am getting invalid cast from double to datetime error when i run my ASP.NET MVC code.
This is my code :
Update: Hi I am adding my full code below. Please have a look into that.
Boolean locked = false;
if (frmcollection["lockStart"] != null && frmcollection["lockStart"] != "")
{
locked = Convert.ToBoolean(frmcollection["lockStart"].ToString());
}
else if (datelock == "")
{
locked = Convert.ToBoolean("0");
}
Boolean valid = true;
double inteval = 86400000 * Convert.ToDouble(frmcollection["autoFrequency"].ToString());
DateTime schedulestartDate = Convert.ToDateTime(frmcollection["autoStart"].ToString());
int startHour = Convert.ToInt32(frmcollection["autoStartHour"].ToString());
DateTime sd = schedulestartDate;
sd.AddHours(startHour);
DateTime filterStart = Convert.ToDateTime(frmcollection["periodStart"].ToString());
int filterStartHour = Convert.ToInt32(frmcollection["periodStartHour"].ToString());
DateTime fsd = filterStart;
fsd.AddHours(filterStartHour);
DateTime filterEnd = Convert.ToDateTime(frmcollection["periodEnd"].ToString());
int filterEndHour = Convert.ToInt32(frmcollection["periodEndHour"].ToString());
DateTime fed = filterEnd;
fed.AddHours(filterEndHour);
double sDate = sd.Second;
double sPeriod = sDate - fsd.Second;
double ePeriod = sDate - fed.Second;
if (sPeriod < ePeriod || sPeriod < 0 || ePeriod < 0)
{
valid = false;
}
if (valid)
{
for (int i = 0; i < 5; i++)
{
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
if (locked)
{
DateTime psdate = Convert.ToDateTime(sDate - sPeriod);
}
else
{
DateTime psdate = Convert.ToDateTime(sDate + (inteval * i) - sPeriod);
}
DateTime pedate = Convert.ToDateTime(sDate + (inteval * i) - ePeriod);
}
}
else
{
}
When i debug I am gettin error in this line :
DateTime date = Convert.ToDateTime(sDate + (inteval * i));
Can someone help me in this??
You're adding a double to whatever interval * i resolves to.
You can't convert (cast) that to a DateTime, which is exactly what the error is telling you.
It seems as if you're looking for the date some (interval * i) seconds after the date "sd". If so, try:
for (int i = 0; i < 5; i++)
{
DateTime date = sd.AddSeconds(inteval * i);
if (locked)
{
DateTime psdate = sd.AddSeconds(-sPeriod);
}
else
{
DateTime psdate = sd.AddSeconds((inteval * i) - sPeriod));
}
DateTime pedate = sd.AddSeconds((inteval * i) - ePeriod);
}
//...
DateTime has a lot of methods to perform calculations on a specific date. For example DateTime.AddMillisecons which takes a double and returns a date.
MSDN DateTime.AddMilliseconds