Date format conversion c# - c#

Guys I have a string having a date in the format dd/mm/YYYY.
However I need to use it a datetimepicker control.
I cannot assign the value to the datetimepicker, i tried as
string exp = "SELECT UserPwdExpiry FROM " + MainForm.schema + "Adm.SysUser WHERE USerId ='" + cmbUserID.Text + "'";
cmd = ccs.CreateCommand();
ccs.Open();
cmd.CommandText = exp;
DateTime expiry_ = ((DateTime)cmd.ExecuteScalar());
//string _expiry_= expiry_.ToShortDateString();
ccs.Close();
assigning here
dtpPasswordExpiry.Value = Convert.ToDateTime(_expiry_);
It gives me an error saying, FORMAT SHOW BE BETWEEN MaxDate and MinDate.
Help please.

if DateTime expiry_ = ((DateTime)cmd.ExecuteScalar()); this line running without errors you already have Datetime object. So you can directly set it as
tpPasswordExpiry.Value =expiry_;
But above line will fail if you store datetime as string in database then
string _User_modify= (string)cmd.ExecuteScalar();
DateTime dt;
if(DateTime.TryParseExact(_User_modify,
"dd/MM/YYYY",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
tpPasswordExpiry.Value =dt;
}

We already have:
DateTime expiry = ((DateTime)cmd.ExecuteScalar());
so: we know the value is a DateTime. The DateTimePicker control's .Value property is a DateTime, so the correct syntax here is:
dtpPasswordExpiry.Value = expiry;
The only thing that leaves, based on the error message, is the MinDate and MaxDate. I suspect you need to change the values of those two properties such that your expiry is a legal value not outside the range MinDate - MaxDate. If unsure, simply print out the values of expiry, dtpPasswordExpiry.MinDate and dtpPasswordExpiry.MaxDate.

Related

c# time to sql date time

I am not able to convert the c# date time7/31/2017 3:13:49 PM to SQL date time while inserting the records to the database.
I am doing this using
DateTime dt = DateTime.Parse("11/23/2010");
string toSqlDate= dt.ToString("yyyy-MM-dd HH:mm:ss");
DateTime finalDate = DateTime.Parse(toSqlDate);
But it's giving me the error.
String was not recognized as a valid DateTime.
The .Net DateTime maps directly to SQL Server DateTime. This means you don't need to worry about the display format at all, since DateTime does not have a display format.
All you need to do is pass the instance of the DateTime struct as a parameter to the SqlCommand:
SqlCommand.Parameters.Add("#DateTimeParam", SqlDbType.DateTime).Value = dt;
Bonus reading: How do I create a parameterized SQL query? Why Should I?
After changing it to year/month/date this can help!
var sqlDate = finalDate.Date.ToString("yyyy-MM-dd HH:mm:ss");
Your dateformat says 'year-month-day' while your date is 'month/day/year', that can't be right. Either change your dateformat or your date's formatting.
This should work:
DateTime dt = DateTime.Parse("2010-11-23 00:00:00");
string toSqlDate= dt.ToString("yyyy-MM-dd HH:mm:ss");
Change query to
insert into table_name (column1) values ('" + dt.Value.ToString("yyyy-MM-dd") + "')
Try the method DateTime.ParseExact and specify The date format that is suitable for you, here is an example from MSDN (https://msdn.microsoft.com/fr-fr/library/w2sa9yss(v=vs.110).aspx) :
var dateString = "06/15/2008";
var format = "d";
try {
var result = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
Console.WriteLine("{0} converts to {1}.", dateString,
result.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}

Convert date and time into Correct format to compare to current date

I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.
Following is how I have
string date = "2017-03-29";
string time = "09:30"
I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq
Use DateTime.ParseExact. Also your problem statement and code shown have nothing to do with Linq. The code below assumes the hours are in 24 hour format, adjust accordingly if that is not the case and provide an am/pm flag.
string date = "2017-03-29";
string time = "09:30";
var dateTime = DateTime.ParseExact(date+time, "yyyy-MM-ddHH:mm", null);
I would say the same as #Sam, but I don't have enough reputation to comment.
string date = "2017-03-29";
string time = "09:30";
string dateTimeString = string.Format("{0} {1}", date, time);
DateTime dateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Note that the Kind of the resulting DateTime is DateTimeKind.Unspecified. Convert it as necessary.
Using the variables provided:
string dateTime = date + " " + time;
DateTime d = Convert.ToDateTime(dateTime);

how can get the date in this format "31-jun-2013"

how can i get the date in this format "30-jun-2013"
at runtime if user type in the above format in the textbox ..it will fetch the matching rows of data for the specified date and filter that and show in datagridview
so for that i want to compare the date format with the text typed in textbox
string todaydate = Convert.ToString(DateTime.Today);
DateTime DTM = Convert.ToDateTime(todaydate);
string datetoday = DTM.ToString("dd-MMM-yyyy");
if (TypeHereTextBox.Text == datetoday)
{
OLCMND2 = new OracleCommand("Select * from TABLENAME where DATE = '" + typeHereTextBox.Text + "'", CON);
OADAP1 = new OracleDataAdapter(OLCMND2);
OADAP1.Fill(DTBLE2);
DatagridView.DataSource = DTBLE2;
}
how can it be solved
hi i got the solution guys
string[] arrayData = TextBox.Text.Split('-');
if (arrayData.Length == 3)
OLCMND2 = new OracleCommand("Select VISITORCOUNT,REMARKS,to_date(to_char(TODAYDATE, 'DD-MON-YYYY'),'DD-MON-YYYY') AS TODAYDATE,CARDNUMBER,PHOTO from VMS_VISITOR where TODAYDATE = TO_DATE('" + TypeHereTextBox.Text + "','dd-MON-yyyy')", CON);
OADAP1 = new OracleDataAdapter(OLCMND2);
OADAP1.Fill(DTBLE2);
DatagridView.DataSource = DTBLE2;
Thanks for all your responses guys
This will parse from that format:
var dateToParse = "30-Jun-2013"; //TypeHereTextBox.Text
var parsedDate = DateTime.ParseExact(dateToParse, "dd-MMM-yyyy", CultureInfo.InvariantCulture);
if (parsedDate.Date == datetoday.Date)
{
// Do stuff
note - June only has 30 days ;)
The best approach would be check for date month and year separately with the today's date. if it matches , then concatenate the date month and year in the format you want and pass to the query.
I would not compare date as strings, fist convert string to DateTime using DateTime.ParseExact by giving datetime format string. then compare two datetime objects instead of string comparison.
And also I would use parameters to set the Date column value as below
OLCMND2 = new OracleCommand("Select * from TABLENAME where DATE = :dateVal", CON);
OLCMND2.Parameters.Add("dateVal", OracleDbType.Date
, myDatetime, System.Data.ParameterDirection.Input);
first of all you are doing string compare, which means you compare the references. please use
if (TypeHereTextBox.Text.Equals(datetoday))
instead.
second, why not comparing dateTime and not strings?
because your data isn't a valid date anyway then you can't use ParseExact or TryParseExact but woth any valid date you can do:
DateTime d;
DateTime.TryParseExact(date, "dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.NoCurrentDateDefault, out d);
if (d== DTM)

removing time from datetime in c# and retaining datetime format

How can I remove time from datetime and store the output in datetime format? I do not want to show the time.
Say I have
string d = "2/27/2013 4:18:53 PM"
How can I store the output in a DateTime variable with only the date and not time.
I can use ToShortDateString() but then it return a string and not datetime.
My ultimate goal is to sort the date column chronologically which can only be done if all the entries are in datetime format and not string.
The Date property of the DateTime struct will give you a date but it will always have a time component that represents midnight ("00:00:00"). If you're starting with a string, you might be able to work with something like this:
DateTime d = DateTime.Parse("2/27/2013 4:18:53 PM").Date; // 2/27/2013 12:00:00 AM
Just make sure you perform your comparison on DateTime objects (i.e. omit all usages of ToString()).
Alternatively, you can format your date in the "sortable" time format:
string d = DateTime.Parse("2/27/2013 4:18:53 PM").ToString("s");
or
string d = yourDateTime.ToString("s");
For the above case d would be 2013-02-27T16:18:53. When sorted alphabetically, the strings will be in chronological order.
DateTime dt = DateTime.now(); (To get Any Date)
string datewithMonth= dt.ToString("MMMM dd, yyyy");
string onlyDate = DateTime.Parse(datewithMonth).ToShortDateString();
Here we get result as 1/1/2014. So that we can perform select operation on sql like this:
searchQuery = "select * from YourTableName where ColumnName = ' " + onlyDate + " ' ";
What about removing the time in culture:-
var submissionDateData = DateTime.Now.ToShortDateString();
var submissionDate = DateTime.Parse(submissionDateData, CultureInfo.CreateSpecificCulture("en-GB"));
First line gives 02/11/2015
Second line gives 11/02/2015 12:00:00 AM
Do you have to do a string split on this or is there a way to get rid of the time?
As easy as this:
d.ToString("mm/dd/yyyy");
DateTime date = DateTime.Parse(d);

DateTime.Parse throwing format exception

I retrieve date and time strings from xml by parsing XElement.
The date and time values are retrieved by
file.Element("Date").Value and file.Element("Time").Value respectively.
After I retrieve the Date value I parse it to a DateTime variable
DateTime dt,ts;
dt = file.Element("Date").Value; // the value is say 12/29/2012
and then this dt value is set to a datepicker value on the xaml UI
datepicker.Value = dt;
I also have a timepicker whose value have to be set by the Time value retrieved from xml.
To set the timepicker value I do the following.
declare 3 strings, say:
string a = file.Element("Time").Value; // the value is say 9:55 AM
string b = file.Element("Time").Value.Substring(0, 5) + ":00"; // eg 9:55:00
string c = file.Element("Time").Value.Substring(5); // the value is ' AM'
I then concatenate the Date Value and string 'b' and 'c'
string total = file.Element("Date").Value + " " + b + c;
the value of total is now '12/29/2012 9:55:00 AM'
I then try to Parse this total string to a DateTime, but it throws a formatexception
DateTime.Parse(total, CultureInfo.InvariantCulture);
Any help appreciated...
Try DateTime.ParseExact
var dateStr = "12/29/2012 09:55:00 AM";
DateTime date = DateTime.ParseExact(dateStr,"MM/dd/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
Demo here.
Read C# DateTime Format for format string detail.
Note that i have added extra 0 to hour part. It must be 2 digits otherwise format exception will occur.
Try using: DateTime.ParseExact
string total = '12/29/2012 9:55:00 AM';
string format = "MM/dd/yyyy H:mm:ss tt";
DateTime dateTime = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
I have got the solution for this.
When trying to save the datepicker in XML format, I was saving the value of timepicker as XMLElement as ValueString, hence when converted to string always throwed error.
So I saved it in XML format as Value.ToString().
Now it can convert correctly from String to Date or Time equivalents.

Categories

Resources