Parse date format as mm-yy from mm/yy [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I wanna convert MM/YY formatted string date to mm-yy DateTime. And set as the value for rad masked edit box. But it returns to me
"String was not recognized as a valid DateTime."
I tried with
DateTime dt = DateTime.ParseExact("11/17", "MMyy", CultureInfo.InvariantCulture);
for eg, I want to convert 03/16 and set value of radmasked edit box masked as MMyy as 03-16

Why do you expect this to work at all?
DateTime dt = DateTime.ParseExact("11/17", "MMyy", CultureInfo.InvariantCulture);
You get a string 11/17 and try to parse it with a format that doesn't contain any delimiters.
This works:
DateTime dt = DateTime.ParseExact("11/17", "MM/yy", CultureInfo.InvariantCulture);
If you want to convert it to a string with this format: MMyy:
string result = dt.ToString("MMyy", CultureInfo.InvariantCulture);
Since it's not clear, if you want this instead: MM-yy
string result = dt.ToString("MM-yy", CultureInfo.InvariantCulture);
It's working for 11/17,12/17. but not in the case of 3/12 etc i.e when
a month is a single digit.
You haven't mentioned that it's possible that the month has a single digit, however:
DateTime dt = DateTime.ParseExact("3/17", "M/yy", CultureInfo.InvariantCulture);

This will work for you.
DateTime dt = DateTime.ParseExact("11/17", "MM/yy", CultureInfo.InvariantCulture);
Then you can convert it to your desired format
string formattedDate = dt.ToString("MM-yy");

In case you want to change delimeter '/' into '-' only, i.e. if you have no need in DateTime temporary value, you can just Replace:
string source = "11/17";
// 11-17: changing '/' to '-'
string result = source.Replace('/', '-');

Related

C# DateTime parses two date strings milliseconds apart incorrectly and gives negative unix time [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I'm trying to convert date strings to Unix time using dotnet 6 and during my testing, I found a strange result between two timestamps that are milliseconds apart. My conversion code is (commented out bits are the variations I've tried and the results are the same):
static long convert_to_unix_time(DateTime date){
return new DateTimeOffset(date, TimeSpan.Zero).ToUnixTimeMilliseconds();
}
static DateTime convert_to_timestamp(string date, string format) {
string[] param = new string[1];
param[0] = format;
var final = new DateTime();
var parsed_time = DateTime.TryParseExact(
date,
param,
CultureInfo.GetCultureInfo("en-ZA"), //CultureInfo.CurrentCulture, //CultureInfo.Invariant,
DateTimeStyles.None,
out final);
return final;
}
Running this:
var date1 = "20201214 13:00:04.156";
var date2 = "20201214 12:59:59.999";
string format = "yyyyMMdd hh:mm:ss.fff";
var final1 = convert_to_timestamp(date1, format);
var unix_time1 = convert_to_unix_time(final1);
Console.WriteLine("final1 is: {0}", final1.ToString(format));
Console.WriteLine("unix time1 is: {0}", unix_time1);
var final2 = convert_to_timestamp(date2, format);
var unix_time2 = convert_to_unix_time(final2);
Console.WriteLine("final2 is: {0}", final2.ToString(format));
Console.WriteLine("unix time2 is: {0}", unix_time2);
The output I get is:
final1 is: 00010101 12:00:00.000
unix time1 is: -62135596800000
final2 is: 20201214 12:59:59.999
unix time2 is: 1607907599999
I can't for the life of me figure out what's causing this error, or even what to call it or search for.
Is there a way to get the correct result?
dotnet fiddle
Uppercase "H" indicates a 24-hour time and lowercase "h" indicates 12-hour time. More information on string formats here.
You are sending a 24h string to a 12h format.
Updated code: https://dotnetfiddle.net/Widget/wkYoQY
string format = "yyyyMMdd HH:mm:ss.fff";
Use "yyyyMMdd HH:mm:ss.fff" instead of "yyyyMMdd hh:mm:ss.fff"

Convert string("2015-03-24T12:31:33.8700000") to c# datetime [duplicate]

This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 7 years ago.
I need to convert a string with date to valid c# date time object.
input string example = "2015-03-24T12:31:33.8700000"
output c# datetime
I tried doing this
DateTime.ParseExact(x.claimDetails.clmDOA, "yyyy-MM-dd HHmmss", CultureInfo.InvariantCulture)
Buit it gave exception
String was not recognized as a valid DateTime
Please Note: I googled thoroghly . Somehow i couldnt find any string
with "T" included as in datetime string.
Prior to downvoting if one can suggest me exactly where a question is answered with datetime string containg a T in it or of this format.yyyy-MM-dd'T'hh:mm:ss.fffffff
DateTime dt = DateTime.Parse(example);
DateTime dt = DateTime.ParseExact(example, "yyyy-MM-dd'T'hh:mm:ss.fffffff", CultureInfo.InvariantCulture);
Should work for you.
From DateTime.ParseExact documentation;
Converts the specified string representation of a date and time to its
DateTime equivalent. The format of the string representation must
match a specified format exactly or an exception is thrown.
In your case, they are not.
You need to use T as a string literal delimiter, specify : as a TimeSeparator and seconds fraction (with fffffff specifier) as well.
var dt = DateTime.ParseExact("2015-03-24T12:31:33.8700000",
"yyyy-MM-dd'T'HH:mm:ss.fffffff",
CultureInfo.InvariantCulture);
DateTime.ParseExact(example , "yyyy MM dd HH:mm:ss", CultureInfo.InvariantCulture);

C# Convert String to Date Time Whereas string has AM : PM formate [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 8 years ago.
Improve this question
I have string time. lets say '06:35 PM'. I want to convert the string to DateTime.
The date must be current time(the day as they input the time).
I did
string times = endTime;
DateTime dt;
(DateTime.TryParseExact(times, "YYYY-MM-dd HH:mm tt", CultureInfo.InvariantCulture,DateTimeStyles.None, out dt))
But it didn't works. it make a null value. because when I try to put the result on label, the label did not show anything. and also I have been try
var date = DateTime.Parse("06:45 AM");
Console.WriteLine(date);
But it didn't works too and it makes an error.
ERROR System.Data.SqlClient.SqlException (0x80131904): The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated. "
How do I convert it ?
I think you are passing the string "06:45 AM" to the database and this is not a valid entry since the DB does not know how to store it, hence the exception.
Looking a bit further, in your first example, YYYY should be lowercase yyyy. YYYY will not parse properly correctly in to a date format.
Considering the second example you have two options:
1) When writing to the database, make sure you pass a valid date, e.g. below. You may need to try a few formats to match up to what your DB expects but it will need a full date and time.
var date = string.Format("{0:yyyy-MM-dd HH:mm tt}", DateTime.Parse("06:45 AM"));
Console.WriteLine(date);
2) Use a full DateTime approach using the correct SQL parameter type. This looks like a good explanation covering a few gotchas. Using DateTime in a SqlParameter for Stored Procedure, format error
If day doesn't matter, you can use following
DateTime date;
if (DateTime.TryParseExact("06:45 AM", new[] {"h:mm tt"}, null, DateTimeStyles.None, out date))
{
Console.WriteLine(date);
Console.WriteLine(date.TimeOfDay);
}
I think the below code will solve your issue;
DateTime dt = DateTime.Now;
TimeSpan ts = new TimeSpan(06, 45, 0);
dt = dt.Date + ts;
To convert string to DateTime format, use the below code;
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);

C# conversion of date from string to date format [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I have a problem with the DateTime.ParseExtract. The error is String was not recognized as a valid DateTime.
trialDate in the sqlserver 2012 is define as folllow type=date and it is display in this format
MM/dd/yyyy. I guess it is the default for sqlserver. I don't know how and where to change it to
dd/MM/yyyy or dd-MM-yyyy.
When I display the date in the listview I did this (put a mask):
'
Here is the C# code-behind
string sTrialDate = "";
foreach (ListViewDataItem item in ListView1.Items)
{
CheckBox MyCheckBox = (CheckBox)item.FindControl("MyCheckBox");
if (MyCheckBox.Checked)
{
Label myTrialDate = (Label)item.FindControl("trialDatelbl");
sTrialDate = myTrialDate.Text;
}
}
The problem is the DATETIME.ParseExtract, here is what I tried so far:
DateTime dt = DateTime.ParseExact("sTrialDate", "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture); <=== not working
DateTime dt = DateTime.ParseExact("sTrialDate", "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture); <=== not working
DateTime dt = DateTime.ParseExact("sTrialDate", "dd/MM/yyyy ",
System.Globalization.CultureInfo.InvariantCulture); <=== not working
DateTime dt = DateTime.ParseExact(Request.QueryString["sTrialDate"], "dd/MM/yyyy", null);
<==not working
You seem to be misusing ParseExact. You are doing:
ParseExact("sDateRdv", "MM/dd/yyyy")
Which is trying to parse the string sDateRdv as a date and obviously failing. If sDateRdv is a variable containing your date then you should use:
ParseExact(sDateRdv, "MM/dd/yyyy")
In your last example you should check what the value of Request.QueryString["sTrialDate"] is. Is it a valid date string?
Lastly you talk about a date in sqlserver and how to change its representation. The answer is you don't really. A date is a date and is independant of how it is displayed. When you look at it it will be converted to a human readable string (because that's all we read) but that doesn't represent how it is stored. You would treat it as a date the whole way (so get it from the database into your C# code as a DateTime) and you only ever convert it to a string for display or maybe some kinds of serialisation (eg XML).
Apart from the fact that you should not pass your variable in quotes:
DateTime dt = DateTime.ParseExact(sDateRdv, "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(sDateRdv, "dd/MM/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(sDateRdv, "dd/MM/yyyy ",
System.Globalization.CultureInfo.InvariantCulture);
You could also try this:
DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
dtfi.ShortDatePattern = "dd-MM-yyyy";
DateTime objDate = Convert.ToDateTime(someStringWithDate, dtfi)

convert date mm/dd/yyyy to yyyy-mm-dd date itself in the format [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying not to format ToString(). I need the date itself in the format.i cannot do to string
scenario:
string str = "02/11/2006";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(str);
now dt is in the format mm/dd/yyyy, but i need in the format yyyy-mm-dd
hope i add some sense..huh!
Not sure what you mean. If you have the date in a DateTime variable it is an universal representation of the date. If you wish to convert it back to string you can use the following:
string str = "02/11/2006";
DateTime dt = new DateTime();
dt = Convert.ToDateTime(str);
var date = dt.ToString("yyyy-MM-dd");
You are confusing the DateTime Structure with its string presentation.
if you want to convert a string with a custom DateTime format you have to use DateTime.ParseExact method
dt = DateTime.ParseExact(str ,"mm/dd/yyyy",CultureInfo.InvariantCulture);
if you want a particular string presentation of a DaTime you have to use a format string
dt.ToString("yyyy-mm-dd")
A DateTime has no format (it's only data). Only String representation have one. Add this to your code :
String newFormatedDate = dt.ToString("yyyy-MM-dd");
I think you just need to know about the ToString overloads:
DateTime newDate = DateTime.ParseExact("15/01/2001", "dd/MM/yyyy", null);
Console.WriteLine(newDate.ToString("yyyy-MM-dd"));

Categories