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);
}
Related
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);
}
I want to compare database datetime value that is stored in dd/mm/yyyy format, with the textbox value that is stored in dd-mmm-yyyy format.
I have tired converting the database value to dd-mmm-yyyy format using parseexact-
DateTime dtdb = DateTime.ParseExact(dr["paydate"].ToString(), "dd-MMM-yyyy",null);
and then comparing with the textbox value,
if(dtdb.ToString() != txtpaydate.Text)
But its giving me this error:
String was not recognized as a valid DateTime.
I also tried doing this:
Convert.ToDateTime(dr["paydate"]).ToString("dd-MMM-yyyy")!= txtpaydate.text
but its still giving me the same error. Please let me know how can I solve this issue. Thank you.
you can convert DateTime value and textbox DateTime value to timestamp (from 1970-0-0) then compare it
edited
maybe you want to read rfc3389 about timestamp
You need to parse your textbox into DateTime object and than you can completely free to use general arithmetic operations such as:
if (dtdb > dttb) and etc. If you have any trouble for parsing it, check this page for further information.
If there's any more question, feel free to ask here. But please check stackoverflow before. Have a great day.
string dtdb =dr["paydate"].ToString("dd-MMM-yyyy");
var dt=txtpaydate.Text.ToString("dd-MMM-yyyy");
if(dtdb!= dt)
{
//do what you want
}
As said, it's best to manipulate pure DateTime objects.
You can do it this way:
// Example strings
var myDate1AsString = "31/12/2016";
var myDate2AsString = "31-dec-2016";
// DateTime object used to retrieved the dates as string
var myDate1AsDate = new DateTime();
var myDate2AsDate = new DateTime();
// Parse the strings; if the parse fail, the date is set to DateTime.MinValue
DateTime.TryParseExact(myDate1AsString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate1AsDate);
DateTime.TryParseExact(myDate2AsString, "dd-MMM-yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate2AsDate);
// Correctly compare the dates
var result = DateTime.Compare(myDate1AsDate, myDate2AsDate);
// or, directly compare a date with the other.
if (!myDate1AsDate.Equals(myDate2AsDate))
{
// Do some stuff.
}
Always use a CultureInfo when parsing date.
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
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);
I have googled alot and tried lot of solutions but nothing is working for me.For Ex i Have tried below :
public static DateTime ParseDateToSystemFormat(DateTime date)
{
IFormatProvider culture = new CultureInfo("en-GB", true);
DateTime dt = DateTime.ParseExact(date.ToString("dd/MM/yyyy"),
"dd/MM/yyyy",
culture,DateTimeStyles.NoCurrentDateDefault);
return Convert.ToDateTime(dt,culture);
}
If anyone have solved this please let me know.
Date objects do not have formatting associated to them - you only use formatting for display.
When it is time to display the DateTime object, use either custom or standard format strings to format the display to your liking.
What you are doing here:
DateTime dt = DateTime.ParseExact(date.ToString("dd/MM/yyyy"),
"dd/MM/yyyy",
culture,DateTimeStyles.NoCurrentDateDefault);
Is rather strange - you are getting a specific string representation of your DateTime - date.ToString("dd/MM/yyyy"), then parsing that string back to a DateTime object. A bit of a long way to say DateTime dt = date;, with clearing out the hours/minutes/seconds data.
If you simply want the date portion of a DateTime, use the Date property. It produces:
A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).
The internal representation of a DateTime is always the same. There is no formatting attached to a DateTime object.
If it is only a display problem, then convert the DateTime to a string and display that string. You already know how to do it: Using ToString and specifying the format you want to have.