Convert string to dd/mm/yyyy in C# WPF - c#

I have a value (as a date) that gets returned from the selected combobox item. I wish to convert this value to a proper DateTime string. Problem is the string from the combobox.selectedItem to convert is;
July 2016
and I want to convert it to (start of month always);
01/07/2016 12:00AM
Is there away of doing the in C#?
As the only way around it is to do I can think of;
if(combobox.selectedItem.Contains("July") && combobox.selectedItem.Contains("2016")) {
//startDate = Set date to 01/07/2016..
endDate = DateTime.Now().ToString();
}
which is not ideal at all...especially if I want do past 24+ months (as combobox is populated with each month between two dates from an xml file)
EDIT/UPDATE
See below working code based of the advice from BOB!
#region try set Date from selected background populated Month
try
{
//param/arg from backgroundWorker
string selectedDate = filterByMonthComboBoxParam;
//Could also be from direct combobox.selecteditem with system string removed
//string selectedDate = filterByMonthComboBox.SelectedItem.ToString().Replace("System.Windows.Controls.ComboBoxItem:", "");
for (int ifilterByMonthComboBox = 0; ifilterByMonthComboBox < filterByMonthComboBox.Items.Count; ifilterByMonthComboBox++)
{
string _filterByMonthComboBox = filterByMonthComboBox.Items[ifilterByMonthComboBox].ToString();
if (_filterByMonthComboBox.Contains(selectedDate)){
DateTime dtX;
if (DateTime.TryParseExact(selectedDate, "MMMM yyyy", null, DateTimeStyles.AllowWhiteSpaces, out dtX))
{
// Parse success
Console.WriteLine(dtX);
checkMinDate = dtX.ToString();
checkMaxDate = nowTime.ToString();
Console.WriteLine("Date Filter is:");
Console.WriteLine("Min: " + checkMinDate);
Console.WriteLine("Max: " + checkMaxDate);
}
else
{
// parse failed
Console.WriteLine("Failed");
}
}
}
}catch(Exception dateError){
Console.WriteLine(dateError);
}
#endregion try set Date from selected background populated Month

DateTime dt;
if (DateTime.TryParseExact("July 2016", "MMMM yyyy", null, DateTimeStyles.None, out dt))
{
// Parse success
Console.WriteLine(dt);
}
else
{
// parse failed
Console.WriteLine("Failed");
}
Checkout DateTime.TryParseExact() and the formats
Edit:
If the date have white space, either use string.Trim() on it or change DateTimeStyles.None to DateTimeStyles.AllowWhiteSpaces

Related

How to input a formatted date in a text box?

I'm confuse about how to make an input of formatted date time and currency. I want user to input the DoB as dd/mm/yyyy but when I'm using DateTime data type in Visual Studio it only get yyyy/mm/dd format.
Here's my code:
This is DoB and property from another class employee.cs
class employee
{
private DateTime myBOD;
public DateTime BOD
{
get
{
return myBOD;
}
set
{
myBOD = value;
}
}
}
This is the main form1.cs
vemployee.BOD = Convert.ToDateTime(bod.Text);
var today = DateTime.Today;
age.Text = Convert.ToString(today.Year-vemployee.BOD.Year);
Well, DateTime is a struct it doesn't have any format but properties like Year, Month, Day etc.
use DateTime.ParseExact when you want to obtain DateTime from string:
vemployee.BOD = DateTime.ParseExact(
bod.Text,
"dd'/'MM'/'yyyy", // Please, note that "mm" stands for minutes, not months
CultureInfo.InvariantCulture);
And .ToString(format) when you want to represent DateTime as a string
DateTime today = DateTime.Today;
bod.Text = today.ToString("dd'/'MM'/'yyyy", CultureInfo.InvariantCulture);

C# Date in CSV file

I have to change a csv file with several dates in it. Every row starts with a date followed whith data.
11-nov-2015,data,data,data
10-nov-2015,data,data,data
9-nov-2015,data,data,data
With the following code I put the data in the right place (20141109 (yyyymmdd))
string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
string[] parts = values[0].Split('-');
if (parts.Length == 3)
{
values[0] = String.Format("{0}-{1}-{2}", parts[2], parts[1], parts[0]);
lines1[i] = String.Join(",", values);
}
}
But two problems remain:
1) The month has to change from nov to 11
2) In the file I download the day for example 9-nov-2014 has to change to 09. for 8-nov-2014 to 08. So an extra 0.
How can this be solved in C#
Instead of making your own datetime format parser, you should use the one already available for you. DateTime.TryParseExact is your tool to convert a string in a date when you know the exact format.
Converting back the date, in the string format that you like, is another task easily solved by the override of ToString() specific for a datetime
string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
DateTime dt;
if (DateTime.TryParseExact(values[0], "d-MMM-yyyy",
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.None, out dt))
{
values[0] = dt.ToString("yyyyMMdd");
lines1[i] = String.Join(",", values);
}
}
I would parse the string into a date and then write it back using a custom date format. From this link we can write this code:
String pattern = "dd-MMM-yyyy";
DateTime dt;
if (DateTime.TryParseExact(values[0], pattern, CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt)) {
// dt is the parsed value
String sdt = dt.ToString("yyyyMMdd"); // <<--this is the string you want
} else {
// Invalid string, handle it as you see fit
}

How to check the date format in given structure

I have passing a date in query string as the format of 02-2014.and using this date I done the search.It is working and the result is perfect .but when I change the query string value in the browser then the error will showing.In this condition I need only some message,So how can we check the query string date value is in correct format.my code is
string dateToSearch = HttpContext.Current.Request["date"];
if (!string.IsNullOrEmpty(dateToSearch))
{
dateToSearch = dateToSearch.Trim();
string year = null;
string month = null;
var dates = dateToSearch.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (dates.Length > 0)
{
month = dates[0];
year = dates[1];
}
}
Just use DateTime.TryParseExact with the format string MM-yyyy. This will tell you whether your input string is in the format you specified and if so, it returns the parsed DateTime object via an out parameter.
Try this:
DateTime date;
if (DateTime.TryParseExact(text, "MM'-'yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
else
{
// Parse failed
}

Best way to bind DateTime to seperate date and time fields?

I use a model class with a DateTime value. I would like to display this property as two boxes, one for the date and the other one for the time.
What is the best way to do this? Any suggestions?
Thanks in advance!
Check this Splitting DateTime Blog post by Hanselman.
Format your datetime in 2 diffent properties.
first to retrieve datetime format as "yyyy/MM/dd"
second format as "HH:mm:ss"
All you need to do is use two format expressions, one to extract the time and the other to extract the date.
Bind this to the date box:
txtDateBox.Text = date.ToString("dd MMM yyyy");
Bind this to the time box:
txtTimeBox.Text = date..ToString("HH:mm:ss");
(Presumign your variable is called date).
You could do something like this (I didn't run the code, it's only an idea):
private DateTime MyModelDateTime;
public string date
{
get
{
return MyModelDateTime.ToString("MM/dd/yyyy");
}
set
{
string pattern = "MM/dd/yyyy HH:mm:ss";
string timeValue = MyModelDateTime.ToString("HH:mm:ss");
string dateTimeValue = value + " " +timeValue;
MyModelDateTime = DateTime.ParseExact(dateTimeValue, pattern, null, DateTimeStyles.None)
}
}
public string time
{
get
{
return MyModelDateTime.ToString("HH:mm:ss");
}
set
{
string pattern = "MM/dd/yyyy HH:mm:ss";
string dateValue = MyModelDateTime.ToString("MM/dd/yyyy");
string dataTimeValue = dateValue + " " + value;
MyModelDateTime = DateTime.ParseExact(dateTimeValue, pattern, null, DateTimeStyles.None)
}
}

How to compare two dates in c#

I have a textbox where i will enter date in mm/dd/yyyy format,i want to compare this textbox date with current date(sysdate) in javascript code in c#.How to do that??Example i enter 11/11/2011 which is future date and it must be checked with sysdate and print an message
example
DateTime.ParseExact(txtDate.Text, "mm/dd/yyyy",null) > DateTime.Today
DateTime dateValue;
string dateString = textBox.Text;
if (DateTime.TryParse(dateString, out dateValue))
{
// Use Date.CompareTo as you want to...
int result = DateTime.Compare(dateValue, DateTime.Today);
if (result > 0)
{
//Future Date
}
}

Categories

Resources