SQL Server VB .NET (or C#) datetime Canonical - c#

I am working with a canonical date in the format 2011-10-24 00:00:00.000.
There is a SQL Server statement that I can run to get the date in the format in that I need it in.
SELECT
CONVERT(VARCHAR(50), CONVERT(datetime, '2011-10-24 00:00:00.000', 120), 101)` as test
Returns
10/24/2011.
Here is my question.
Is there a way to do this, convert '2011-10-24 00:00:00.000' to 10/24/2011, in .Net (C# or VB) ?

Why don't you just select it as a date instead of converting to VARCHAR(50) ?
If That's not an option then cast it to a date (DateTime.Parse) and use the properties on the datetime.

In VB
Dim dt As Date = Date.Parse("2011-10-24 00:00:00.000")
Dim newDateString as string = dt.ToShortDateString()
In C#
System.DateTime dt = System.DateTime.Parse("2011-10-24 00:00:00.000");
string newDateString = dt.ToShortDateString();

VB.Net
Dim newDate As string = CDate(fromdb).ToShortDateString
c#
string newDate = DateTime.Parse(fromdb).toShortDateString();
pull it from db as a DateTime , let c# / vb.net convert for you

You can parse input string to DateTime object with DateTime.Parse and then format it as you wish with DateTime.ToString method.

Related

Mismatches on DateTime between C# and SQL server

I create DateTime in C# like this
DateTime oDate = Convert.ToDateTime(xate);
that returns 22/09/2020 01:27:00 ب.ظ}
and save it in SQL server after saving I see the time that stored is Weird
like this
and when I try to run a SQL command like this
INSERT INTO HomeVisit (LifeplusCaseId, FromDateTime, ToDateTime)
VALUES ('39909F03-2DEF-4682-89CA-0000DCC3E098','22/09/2020 12:00:00 ق.ظ', '22/09/2020 12:00:00 ق.ظ');
I get this error
Conversion failed when converting date and/or time from character string.
I figure out the time that generates in C# is vice versa the format in the SQL Server.
I don't know how to save DateTime in C# to SQL Server.
My code for saving datatime in SQL Server is:
HomeVisitRow homeVisit = BehzistiDb2.List<HomeVisitRow>().Where(x => x.LifeplusCaseId == lifeplusCaseId && x.FromDateTime <= oDate && x.ToDateTime > oDate).FirstOrDefault();
if (homeVisit == null)
{
homeVisit = new HomeVisitRow
{
Id = Guid.NewGuid(),
LifeplusCaseId = lifeplusCaseId,
FromDateTime = oDate,
ToDateTime = oDate.AddMonths(6)
};
BehzistiDb2.Insert<HomeVisitRow>(homeVisit);
Conversion failed when converting date and/or time from character
string
The problem is that you insert a string ' ' into your SQL Database instead of a DateTime Object like you specified.
We can create a DateTime Object from a string easily if we use DateTime.TryParseExact()
Example:
DateTime fromDate;
string txtStartDate = "22/09/2020 01:27:00";
DateTime.TryParseExact(txtStartDate, "dd/MM/yyyy HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out fromDate);
Console.WriteLine(fromDate.ToString());
Now we can also insert that Variable into our SQL Statement as it's value.
INTO HomeVisit (LifeplusCaseId, FromDateTime, ToDateTime)
VALUES ('39909F03-2DEF-4682-89CA-0000DCC3E098', fromDate, toDate);
You format the date according to your requirement just see the below examples.
DateTime oDate = Convert.ToDateTime(xate);
oDate = oDate.ToString("yyyy-MM-dd");

How to convert this date 2017-07-09T17:50:21.000-0500 | C#

when i run the below code,
string dt = "2017-07-09T17:50:21.000-0500";
DateTime date = Convert.ToDateTime(dt);
it gives me output as
7/10/2017 4:20:21 AM
where as i want my output to be
2017-07-09 17:50
update
the code #alexander-petrov gave worked
string dt = "2017-07-09T17:50:21.000-0500";
string date = DateTimeOffset.Parse(dt).DateTime.ToString("yyyy-MM-dd HH:mm");
gives output
2017-07-09 17:50
but on inserting the same to database it is adding +5 hrs to the time and inserting as
2017-07-09 22:50
This is a Round-Trip format of a DateTime specified with a DateTimeKind.Local kind.
You need to decide if your program needs to be aware of time zones or not.
You could try parsing it while supplying the System.Globalization.DateTimeStyles.RoundtripKind or System.Globalization.DateTimeStyles.AdjustToUniversal parameter to the Parse method.
If you want take offset into account then use DateTimeOffset type.
string dt = "2017-07-09T17:50:21.000-0500";
DateTimeOffset date = DateTimeOffset.Parse(dt);
// format on my machine
// 09.07.2017 17:50:21 - 05:00
Console.WriteLine(date);
// without offset
// 09.07.2017 17:50:21
Console.WriteLine(date.DateTime);
I couldn't get your date to work, as I think there is a colon missing in the last part. Adding that colon back allows me to convert the XSD date time into a SQL DATETIME using this script:
DECLARE #stringDate VARCHAR(30);
SELECT #stringDate = '2017-07-09T17:50:21.000-05:00';
DECLARE #xmlDate XML;
SELECT #xmlDate = CAST('' AS XML);
SELECT #xmlDate.value('xs:dateTime(sql:variable("#stringDate"))', 'datetime');
Results:
2017-07-09 22:50:21.000
Try:
string date = "2017-07-09T17:50:21.000-0500";
DateTime d = DateTime.ParseExact(date, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzzz", null);

How to convert dd/mm to Mysql Datetime format in c#

I have a date string with dd/mm format like 06/03.Now i have to store this string into mysql table column with DATETIME format.
I am getting the problem as How can i add the current year generically because i don't want to hard code it.Subsequently how will i convert it into MySql DATETIME format for saving it.
Please help me .
You can use Parse method of DateTime:
DateTime dateTime = DateTime.Parse("06/03");
UPDATE
For your comment:
Also after parsing into DateTime i am getting date correct but time i
dont want to be 12:00:00 AM instead i want it to be 00:00:00.
12:00:00 AM corresponds to 00:00:00 only. You can verify that by getting Hour property which will return 0 and also TimeOfDay will too return 00:00:00.
Even if you try to parse exact date, it also creates the same format.
DateTime dateTime = DateTime.ParseExact("06/03 00:00:00", "dd/MM hh:mm:ss",
CultureInfo.InvariantCulture);
And you don't need conversion from DateTime object to SQL compliant DateTime object. You can pass the .Net object to SQL writer.
Consider the code:
C#
string s = "06/03";
System.DateTime dateNow = Convert.ToDateTime(s);
will give the output as you required
in VB.Net :
Dim s As String = "06/03"
Dim dateNow As Date = CDate(s)
MsgBox(dateNow)
You could do something like
var some_date = "06/03";
var year = DateTime.Now.Year;
var option = some_date+"/"+year;
Or use any of the string formats to bend it to your needs
More on date string format can be found on this MSDN page.
Edit:
If you want zeroes in the time, like your comment said, you can usit Rohit vats answer and do:
DateTime dateTime = DateTime.Parse("06/03");
var s1 = dateTime.ToString("MM/dd/yy 00:00:00");
// Output: 03/06/14 00:00:00
var s2 = dateTime.ToString("MM/dd/yyyy 00:00:00");
// Output: 03/06/2014 00:00:00

convert back datetime format toLongdatestring to (M/DD/YYYY h/mm/ss)

hi i have datetime format in database like this
1/18/2014 4:14:52 PM (M/DD/YYYY h/mm/ss)
i convert it to ToLongDateString
string date = Convert.ToDateTime(myQuizOccurrence.occurred).ToLongDateString();
**result ->** **Sunday, January 12, 2014**
i want to convert back again that result date to become same format as database i wonder how to do it?
edited
so far i already try as #matt says using datetime instead string
DateTime dt2 = (DateTime) myDataGridView.CurrentRow.Cells[3].Value;
i already check it's have same format as datetime in database
but when i try to matching in query with this following code
Global.dbCon.Open();
string kalimatsql2 = "SELECT * FROM Quiz_Occurrences WHERE Occurred = " +dt2+ "
ORDER BY ID";
Global.reader = Global.riyeder(kalimatsql2);
if (Global.reader.HasRows) {
while (Global.reader.Read()) {
int idku = Convert.ToInt32(Global.reader.GetValue(0));
MessageBox.Show(idku.ToString());
}
}
Global.dbCon.Close();<br>
it's give error result
Syntax error (missing operator) in query expression 'Occurred = 1/12/2014 4:18:59 PM'
what i'm missing?
The vast majority of databases you will interact with should be accepting either a DateTime or a DateTimeOffset type directly. You would not use a string when retrieving data from the database, nor when sending data back to it. Therefore, format is irrelevant.
My guess is you are doing something similar to this:
DateTime dt = Convert.ToDateTime(mydatareader["MyDateTime"].ToString());
Instead you should be doing this:
DateTime dt = (DateTime) mydatareader["MyDateTime"];
When you save it back to the database, you should be using parameratized inputs that will take the DateTime directly. If you're trying to concatenate a string to build an SQL statement, you're doing it wrong.
i have datetime format in database like this
The best practice is to store date and time information with DateTime or DateTimeOffset type.
To convert back your string to DataTime you can use this:
string str = "Sunday, January 12, 2014";
var dateTime = DateTime.ParseExact(str, "D", CultureInfo.CurrentCulture);
Note that you loss the time part when you convert it to long date.

DateTime format for c#

I'm writing some dates to sql from a text file. In text file date format like 10.01.2013(dd.mm.yyyy) but when i write it on sql it seems `2013-01-10 what should to add it as 10.01.2013
Here is my code:
en.LogDateTime = DateTime.Parse(myDateString);
you can use the DateTime.ParseExact method to specify exactly what format your input string should be
DateTime dt = DateTime.ParseExact("10.01.2013", "MM.dd.yyyy", CultureInfo.InvariantCulture);
DateTimeFormatInfo dateformat= new DateTimeFormatInfo();
dateformat.ShortDatePattern = "dd.MM.yyyy";
dateformat.DateSeparator = ".";
DateTime objDate = Convert.ToDateTime(strDate, dateformat);
if you want to specify the format while inserting the data into table you can use following sql query:
dateformat dmy;
insert into mytable values(mydatetime);

Categories

Resources