Convert US Date To UK Date Format C# - c#

All,
I'm really new to C# after years of VBA Programming. I have made an attempt at trying to convert a US date which is passed into the script via a parameter into a UK date. (Apologies if this is a really basic question - I am still working through training materials)
The issue I am having is passing the UK date out as a parameter.
Code below:
using System.Globalization;
namespace Dynamic.Script_8D643DCA79B170B
{
// Please use caution when modifying class name, namespace or attributes
[OpenSpan.TypeManagement.DynamicTypeAttribute()]
[OpenSpan.Design.ComponentIdentityAttribute("Script-8D643DCA79B170B")]
public sealed class Program
{
public void Dateformat(Datetime USdate, Datetime UKdate)
{
string value = USdate;
string format = "dd/MM/yyyy";
DateTime result;
if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
Console.WriteLine(result.ToString(format));
}
else
{
Console.WriteLine("Date invalid");
}
}
}
}
Essentially I would like to pass a date formatted as MM/dd/YYYY into the script and convert it into UK date format dd/MM/YYYY as a variable. Any help and guidance on how to adapt the above script would be much appreciated.
*****Edit**********
Thanks for all your help and advice so far, I have been able to develop a new script see below:
public string Dateformat(string USdate)
{
string date = USdate; // en-US formatted date
// Convert to DateTime
DateTime parsedDate = DateTime.ParseExact(date, "MM/dd/yyyy", CultureInfo.InvariantCulture);
// Output in en-GB format
return parsedDate.ToString("dd/MM/yyyy");
}
The issue I am having with the above script is that the string was not recognized as a valid DateTime. See screenshot:
The USdate I am passing into the script is formatted in DateTime.

Related

How to convert this UTC datetime string to DateTime object c#

I have been trying to convert this string to a DateTime object in C#
2019-09-23T08:34:00UTC+1
I've tried using DateTime.Parse but it is throwing an exception for
"String was not recognized as a valid DateTime."
I'm sorry but you seem like a victim of garbage in, garbage out.
That's an unusual format, that's why before I suggest a solution for you, first thing I want to say is "Fix your input first if you can".
Let's say you can't fix your input, then you need to consider a few things;
First of all, if your string has some parts like UTC and/or GMT, there is no custom date and time format specifier to parse them. That's why you need to escape them as a string literal. See this question for more details.
Second, your +1 part looks like a UTC Offset value. The "z" custom format specifier is what you need for parse it but be careful, this format specifier is not recommended for use with DateTime values since it doesn't reflect the value of an instance's Kind property.
As a solution for DateTime, you can parse it like I would suggest;
var s = "2019-09-23T08:34:00UTC+1";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd'T'HH:mm:ss'UTC'z", CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal, out dt))
{
Console.WriteLine(dt);
}
which gives you 2019-09-23 07:34:00 as a DateTime and which has Utc as a Kind property.
As a solution for DateTimeOffset - since your string has a UTC Offset value you should consider to parse with this rather than Datetime
-, as Matt commented, you can use it's .DateTime property to get it's data like;
var s = "2019-09-23T08:34:00UTC+1";
DateTimeOffset dto;
if(DateTimeOffset.TryParseExact(s, "yyyy-MM-dd'T'HH:mm:ss'UTC'z", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dto))
{
Console.WriteLine(dto.DateTime);
}
which gives you the same result DateTime but Unspecified as a .Kind property.
But, again, I strongly suggest you to fix your input first.
Use TryParseExact to convert the string to datetime. Here is the sample code to covert the given format(s) to datetime
private static DateTime ParseDate(string providedDate) {
DateTime validDate;
string[] formats = {
"yyyy-MM-ddTHH:mm:ss"
};
var dateFormatIsValid = DateTime.TryParseExact(
providedDate, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out validDate);
return dateFormatIsValid ? validDate: DateTime.MinValue;
}
Then, use this function to convert the string. I am replacing UTC+1 to empty string
static void Main(string[] args) {
string strdatetime = "2019-09-23T08:34:00UTC+1";
DateTime dateTime = ParseDate(strdatetime.Replace("UTC+1", ""));
Console.WriteLine(dateTime);
}

how to input DateTime into MySQL via C#

I'm having a huge issue with inputting DateTime into my MySQL db. MySQL reads datetime as yyyy-MM-dd HH:mm:ss while C# sees datetime as dd/MM/yyyy HH:mm:ss. I have tried two different examples and both doesn't work.
MODEL
public class DateAndTime
{
public DateTime DateTime { get; set; }
}
CONTROLLER
//I Have two examples that doesn't work.
var myDateTime = "2016-04-08 12:00:00" //this gives the error "cannot covert source 'string' to tartget type System.DateTime
var myDateTime = Convert.ToDateTime("2016-04-08 12:00:00") //this gives the error "Input string was not in a correct format."
var model = new DateAndTime
{
DateTime = myDateTime
};
So I'm stuck. I'ms sure someone out there has had this issue.
DateTime myDate = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture);
Check:
Converting a String to DateTime
https://msdn.microsoft.com/en-ca/library/cc165448.aspx
https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
I have this issue because of the datetime format in my machine. If your desktop is configured like dd/mm/yy(the / symbol instead of -) then you have to replace - with / before converting. Please let me know
try this :
myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
myDateTime variable must be type DateTime.
or you can use this MySql function : STR_TO_DATE
STR_TO_DATE('4/8/2016 2:18:17 PM', '%m/%d/%Y %h:%i:%s %p')
Specifier Format here

ways to check if datetime is valid [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I searched in SO, but was not able to find responses that would work for me.
I have a dateTime value in c# and I would like to check if its got a valid value .For example if the following value is passed to datetimeupdate(which is of type datetime) I should be able to throw an exception .
datetimeupdate= 2015-07-29T19:55:10.994sdfsdf
I tried using Tryparse but it accepts string as the first parameter. But the datetimeupdate parameter is of type datetime. I am not sure how to check if the parameter has valid value.
I cannot do front end validition as this is in WebAPI and thats the value I get(with invalid characters)
What you have a string representation of a datetime. You can use TryParse() method like below; which will return TRUE if parsing succeeds.
static void Main(string[] args)
{
string str = "2015-07-29T19:55:10.994sdfsdf";
Console.WriteLine(IsvalidDateTime(str));
}
static bool IsvalidDateTime(string date)
{
DateTime dt;
return DateTime.TryParse(date, out dt);
}
using System;
public class Program
{
public static void Main()
{
try
{
string d = "2015-07-29T19:55:10.994sdfsdf";
DateTime dt = Convert.ToDateTime(d);
Console.WriteLine(dt);
}
catch(FormatException)
{
Console.WriteLine(" Date is InValid ");
}
}
}
DateTime formats quite extensively between different countries/regions.
For instance here in Sweden we follow the ISO 8601-format — yyyy-MM-dd. In the US, the standard format is M/d yyyy
So as for a the "validity" of a date; it's hard to say.
One might describe the date as 2015-07-29T19:55:10.994sdfsdf.
And it could be valid if your program could handle (and parse) that input.
The easiest solution to your problem is to use DateTime.Parse or DateTime.TryParseExact (if you know what format your date is in)
string dateString = "2015-07-30 18:00:00.142"
string dateFormat = "yyyy-MM-dd HH:mm:ss.fff"
DateTime parsedDate;
bool parseSuccess = DateTime.TryParseExact(
s: dateString,
format: dateFormat,
provider: CultureInfo.CurrentCulture,
style: DateTimeStyles.None,
result: out parsedDate
);
if (parseSuccess)
{
// valid
}
else
{
// not valid
}
If the format of the string-representation of the DateTime is unknown, you may use DateTime.Parse or DateTime.TryParse.
string dateString = "2015-07-30 18:00:00.142"
DateTime parsedDate;
if (DateTime.TryParse(dateString, out parsedDate))
{
// valid
}
else
{
// not valid
}
However, even though used quite extensively — these come with no guarantee of parsing a "correct" date, since the end-user might have entered the date in a different format than expected. And you might end up with the hours in place of the months; which could have some quite unexpected consequences.
Some reading
Custom DateTime-formats.
DateTime.TryParse
DateTime.TryParseExact

Convert 2015-06-01T02:31:00+0000 to DateTime object c#

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.

Error while converting string to DateTime after publishing to web server

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);

Categories

Resources