I have a form where the user selects the Date from the UI .
I am getting the following value from UI
var uiDate = "2019-05-03T00:00:00.000Z".
I need to convert this to DateTime for further processing .
var dt = Convert.ToDateTime(uiDate);
The value of dt is "5/2/2019 8:00:00PM" .
As we can see I am always getting one day back after DateTime conversion from the date selected from UI. I was expecting "5/3/2019".
I am not able to figure out why is this happening after DateTime conversion?
Convert.ToDateTime is implicitly converting the value to local time. If you use DateTime.ParseExact, you can specify appropriate conversion options:
using System;
using System.Globalization;
class Program
{
static void Main()
{
string text = "2019-05-03T00:00:00.000Z";
DateTime parsed = DateTime.ParseExact(
text, // The value to parse
// The pattern to use for parsing
"yyyy-MM-dd'T'HH:mm:ss.FFF'Z'",
// Use the invariant culture for parsing
CultureInfo.InvariantCulture,
// Assume it's already in UTC, and keep it that way
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Console.WriteLine(parsed); // 03/05/2019 00:00:00 (on my machine; format will vary)
Console.WriteLine(parsed.Kind); // Utc
}
}
Related
So I am getting the driver date from graphic card and display it into a TextBox but the value comes like this 20161216000000.000000-000 and I want to convert it into a real date.
I already got a function to convert this kind of dates, but it this case does does not work and after using it shows me like this 01-01-0001 00:00:00.
This is my function code:
private static string FormatDateTime(object ObjInstallDate)
{
object FinalDate = DBNull.Value;
string strDate = Convert.ToString(ObjInstallDate);
DateTime dtm;
DateTime.TryParseExact(strDate, new string[] { "yyyyMMdd", "yyyy-MM-dd", "dd-MM-yyyy" },
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtm);
if (!String.IsNullOrEmpty(strDate))
{
FinalDate = dtm;
}
return FinalDate.ToString();
}
Do you have any idea how I can get in this case 20161216000000.000000-000 something like 2016-12-16?
Taking a substring does the job (if the format is always like shown):
DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out DateTime dtm);
To get the required format to present the result you can use
dtm.ToString("yyyy-MM-dd");
After looking at your code and question it looks like the date you are passing to the function is not in correct/expected format that c# supports, that's why it is giving you the default system's beginnning date which is 01-01-0001 00:00:00 here.
But, as a workl around, as I can observe first 8 digit of the input value is date part, so you can use that in following way:
DateTime.TryParseExact(strDate.Substring(0, 8), "yyyyMMdd",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out dtm);
return dtm.ToString("yyyy-MM-dd");
You only needed to make sure your format matched your input, which none of your provided input formats did.
See how the custom dateformat specifiers and literal characters line-up with your input.
Your input: 20161216000000.000000-000
format specifiers: yyyyMMddhhmmss.ffffff-000
Bringing that format to your method you'll get this:
// takes an object, returns a DateTime or null in case of failure
DateTime FormatDateTime(object ObjInstallDate)
{
DateTime dtm;
if (!DateTime.TryParseExact(
(string) ObjInstallDate, // notice that we don't hassle with the input here,
// only cast to a string
// we simply rely on the parser of DateTimer.TryParseExact
"yyyyMMddhhmmss.ffffff-000", // this matches the format
// if the -000 represents a timezone
// you can use z00 or zz0
// don't use zzz as that expects -0:00
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out dtm))
{
// an invalid date was supplied, maybe throw, at least log
Console.WriteLine("{0} is not valid", ObjInstallDate);
}
// we either return here null or a valid date
return dtm; // !! No ToString() here
}
I cherry picked the needed custom format value from Custom Date and Time Format Strings.
Notice that I simply return the DateTime instance that was created. You'll see next why I do that.
As you want to display the DateTime on a Winform (I assume in a textbox, but an label will work as well) you can now simply Databind the DateTime instance to the textbox and let the databinding plumbing do the formatting. Here is a code example that can be run in LinqPad:
// take a string and make a date of it
var str = "20161216000000.000000-000";
DateTime dtm = FormatDateTime(str);
// show it on a Databind TextBox
var f = new Form();
var txt = new TextBox();
txt.Width = 200;
// bind the Text property
txt.DataBindings.Add(
"Text", // property on the textbox
dtm, // our DateTime object
null, // use the DateTime instance, not a property
true, // use formatting
DataSourceUpdateMode.OnValidation,
null, // value to indicate null
"yyyy-MM-dd"); // our format
f.Controls.Add(txt);
f.Show();
I'm using the overload of Add on the DataBindingsCollection that takes an Format string. I can then use the same custom format specifier options to represent that DateTime instance however I want. From here it would be easy to add another TextBox which uses the same DateTime instance but shows the month in text for example.
When all of this comes together this will be your result:
I'm writting an app that consume this webservice:
http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json
as you can see there, the JSON object comes with an utc datetime field. I want to save this information in a simple DateTime object with the following format "yyyy-MM-dd HH:mm:ss".
This is my code:
DateTime dateParsed = DateTime.Now;
DateTime.TryParseExact((string)resource.SelectToken("resource").SelectToken("fields")["utctime"], "yyyy'-'MM'-'dd'T'HH':'mm':'ssz", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out dateParsed);
I'm getting an DateTime object initialized in the year 0001.
What I'm doing wrong?
You should be using the K custom format specifier (instead of z).
string s = "2015-06-01T04:41:10+0000";
DateTime dt = DateTime.ParseExact(s, "yyyy-MM-dd'T'HH:mm:ssK",
CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal);
It will read the +0000 as the offset. Then by using the AdjustToUniversal style, the resulting DateTime will also be in terms of Universal time, having DateTimeKind.Utc.
Also, since you're reading from a known data source, there's no real benefit of using TryParseExact. The format from your data source is fixed, so just use ParseExact with that format. The Try... methods are primarily for validating user input, or when the source format could vary.
One last point - if you just parse your data using JSON.net, that format should automatically be recognized. You just use a DateTime or DateTimeOffset property, and it would parse it without issue.
You have just an error in your Format-String. This is a working sample:
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
DateTime dateParsed = DateTime.Now;
if ( DateTime.TryParseExact( "2015-06-01T02:31:00+0000", "yyyy-MM-ddThh:mm:ss+0000", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal, out dateParsed ) ) {
Console.WriteLine(string.Format("Parsing done: {0:MM/dd/yyyy # hh:mm}", dateParsed ) );
} else {
Console.WriteLine("No result");
}
}
}
Note: the +0000 is hardcoded, when you get other values you would need to detect them. If the api returns only +0 values, you could cut them off and work without z.
I got a problem when trying to convert a date-time format with SAP RFC.
I'm trying this:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
IRfcFunction SAPRateAPI = null;
SAPRateAPI = _ecc.Repository.CreateFunction("ZRFC_CUST_CONDITION_RATE");
SAPRateAPI = CreateSAPRateAPI(SAPRateAPI, argPartnerSAPTranCode, argCustSAPTranCode, argMaterialCode, date);
SAPRateAPI.Invoke(_ecc);
But getting an error 'Specified Cast is not valid'
DateTime in C# has its own representation and doesn't has any "format" which you can see or change.
So phrase "datetime in dd.mm.yyyy format" has no sense at all.
Let's look at your code:
string tmpDate = argDate.ToString("dd.MM.yyyy");
DateTime date = Convert.ToDateTime(tmpDate);
Here you're converting DateTime to string and then back to DateTime.
You're getting exception on back cast just because Convert uses your windows specified culture, and in the case it differs from the one in the string - you need DateTime.ParseExact and explicit format specification.
But even if this cast will be successful - you again will get DateTime and this two lines will not change its format.
It looks like all you need - is just pass date only part of datetime as argument of your function. But it can be achieved pretty easily without any casts just by using argDate.Date (assuming agrDate is DateTime)
DateTime date = new DateTime( argDate.Years, argDate.Month, argDate.Day );
I think this is what you want.
See: C# Reference
Edit:
Which is the same as Andy Korneyev solution - Ok, his is nicer too look at, but both create a second DateTime object.
Consider using the DateTime.ParseExact method.
// Parse date and time with custom specifier.
string format = "dd.mm.yyyy hh:mm:tt";
DateTime date;
try {
date = DateTime.ParseExact(argDate, format, CultureInfo.InvariantCulture);
}
catch (FormatException e) {
throw new ArgumentException("argDate", e);
}
I have a datetime stored in the database as GMT. I need to format this datetime as a string together with the timezone offset to UTC, for example:
DateTime date = DateTime.Parse("2012-03-15 12:49:23");
string dateAsString = date.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz");
2012-03-15T12:49:23.000+00:00
This code works on my machine in the UK. When I change my regional settings to a different time zone, for example Perth, I get the following output:
2012-03-15T12:49:23.000+08:00
I need the string output to always represent the time in GMT.
It's awkward. First you need to parse it appropriately, then format it appropriately... it's easiest to go via DateTimeOffset. (I'm assuming you intend the input string to be treated as if it's in UTC? You haven't made this clear.)
You can use DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal so that you end up with a UTC value after the Parse step. You can then create a DateTimeOffset from that DateTime value, so it will have an offset of 0.
Assuming you have a fixed format input, I would strongly advise that you use DateTime.ParseExact instead of DateTime.Parse, too. (Actually, I'd probably advise you to use Noda Time instead, but that's a different matter...)
Sample code:
using System;
using System.Globalization;
class Test
{
static void Main()
{
var parsed = DateTime.ParseExact("2012-03-15 12:49:23",
"yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal |
DateTimeStyles.AdjustToUniversal);
var dtOffset = new DateTimeOffset(parsed);
var output = dtOffset.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz",
CultureInfo.InvariantCulture);
Console.WriteLine(output);
}
}
I am using below code
DateTime dtt=new DateTime();
dtt = Convert.ToDateTime(FromDate);
// DateTime dtt = DateTime.Parse(FromDate); //this also gives the same error
con = new MySqlConnection(conString);
con.Open();
for (int i = 1; i <= TotalDays; i++)
{
string updateHotelBooking = "Update tbl_hotelbookingdetail set `BookedRoom`=`BookedRoom`+"+1+", `AvailableRoom`=`TotalRoom`-`BookedRoom` where `HotelID`="+HotelID+" AND `CurrentDate`='"+dtt.ToString("dd-MM-yyyy")+"'";
MySqlCommand cmd7=new MySqlCommand(updateHotelBooking,con);
cmd7.ExecuteNonQuery();
dtt = dtt.AddDays(1);
}
This code is in one of my webservice which I am using for iPhone application.
here FromDate is string with value in this formate 15-11-2011 which is coming from the application in string format. I am converting it to DateTime because in loop of total days
I need to add day to dtt.
It is working fine on local host with dtt value 15-11-2011 00:00:00
but when I published it,it gives error
String was not recognize as valid DateTime
This is almost certainly because your server uses a different culture by default - and your code is just using the current thread culture.
You can specify this using DateTime.Parse - or specify the pattern explicitly with DateTime.ParseExact or DateTime.TryParseExact - but we need to know more about where the string is coming from to suggest the best approach. Is it from the user? If so, you should use the user's culture to parse it. Is it a specific format (e.g. from an XML document) instead? If so, parse using that specific format.
Ideally, get rid of the string part entirely - if you're fetching it from a database for example, can you store it and fetch it as a DateTime instead of as a string? It's worth trying to reduce the number of string conversions involved as far as possible.
EDIT: To parse from a fixed format of dd-MM-yyyy I would use:
DateTime value;
if (DateTime.TryParseExact(text, "dd-MM-yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal,
out value))
{
// Value will now be midnight UTC on the given date
}
else
{
// Parsing failed - invalid data
}
What are you culture settings on your local machine and on the server?
The DateTime conversion is dependent on the current culture - dates are written quite differently in different countries.
One way to make the conversion "predictible" is to use the invariant culture:
DateTime dtt = Convert.ToDateTime(FromDate, CultureInfo.InvariantCulture);
the server date format may be in mm/dd/yyyy and you are trying to pass dd/mm/yyyy
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] dateValues = { "30-12-2011", "12-30-2011",
"30-12-11", "12-30-11" };
string pattern = "MM-dd-yy";
DateTime parsedDate;
foreach (var dateValue in dateValues) {
if (DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate))
Console.WriteLine("Converted '{0}' to {1:d}.",
dateValue, parsedDate);
else
Console.WriteLine("Unable to convert '{0}' to a date and time.",
dateValue);
}
}
}
// The example displays the following output:
// Unable to convert '30-12-2011' to a date and time.
// Unable to convert '12-30-2011' to a date and time.
// Unable to convert '30-12-11' to a date and time.
// Converted '12-30-11' to 12/30/2011.
Check this for more details
Log (or otherwise provide feedback to yourself) what FromDate is. Maybe it's empty?
May the Language Settings on the Server are different so it does not recognize the dd-MM-yyyy - try using DateTime.ParseExact(dateString, "dd-MM-yyyy", CultureInfo.InvariantCulture);