Cannot convert date into specific format - c#

I'm trying to convert a Date into a specific format, I saw a lot of questions here with the same target but all the proposed solutions return a string, I need to return a DateTime in my custom format.
This is my code:
private DateTime? _matchCalendarDate = DateTime.Now;
public DateTime? MatchCalendarDate
{
get
{
var date = _matchCalendarDate.Value.ToString("dd-MM-yyyy");
var c = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
return c;
}
set
{
_matchCalendarDate = value;
OnPropertyChanged();
}
}
this return: 8/15/2018 12:00:00 AM but should return 15/08/2018

When you say it returns 8/15/2018 12:00:00 AM, I'm guessing you're simply calling ToString() on the property, like so:
MatchCalendarDate.ToString();
The thing is, a DateTime object doesn't have it's own inherent 'format'. It's format is whatever you want it to be.
So when you actually use the property to print the value it returns, you can choose how you want it do be displayed.
Something like;
MatchCalendarDate.ToString("dd-MM-yyyy");
But then, that essentially renders the conversion in your property redundant. So assuming your intention is to store a DateTime object, but retrieve it in the format you like, what you should do is declare a second string property that does the conversion for you.

Return matchCalendarDate.Date; returns the date component, time set to zero

You may have to consider converting to the original format first then to your required format
private DateTimeDateTime _matchCalendarDate, _matchCalendarD = DateTime.Now;
public DateTime MatchCalendarDate
{
get
{
var date = _matchCalendarDate.Value.ToString("dd-MM-yyyy");
var dt = DateTime.ParseExact(date, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
var c = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
return c;
}
set
{
_matchCalendarDate = value;
OnPropertyChanged();
}
}

Related

Converting DateTime format

I am trying to convert a string, 20151107 to the date format of 2015-11-07.
Here's my code :
public static DateTime CustomDateFormat(this string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt;
}
However this returns something like this 11/07/2015 12:00:00 AM.
Any idea?
Your date returns like that because you are returning the entire DateTime object and since you are not providing a time it is default to 00:00:00.00.
If you want to return the Date in a particular format, you can use the Standard Format Strings or a Custom Format String.
In your case, you want 2015-11-07 which is a custom format of yyyy-MM-dd and can be used like so:
public static string CustomDateFormat(string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt.ToString("yyyy-MM-dd");
}
public static String CustomDateFormat(this string resultdate)
{
DateTime dt = DateTime.ParseExact(resultdate, "yyyyMMdd", CultureInfo.InvariantCulture);
return dt.ToString("yyyy-MMM-dd");
}

How to parse the date time string including the milliseconds using c#?

I am trying to convert a datatime string "including milliseconds" into a DataTime. I tried tried to use DateTime.TryParseExact but it does not give me a milliseconds.
Here is what I have tired
public static DateTime? dateTimeVal(string raw, string format = null)
{
DateTime final;
if(raw != null){
if( format != null){
string[] formats = new[] { format };
if (DateTime.TryParseExact(raw, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out final))
{
return final;
}
}
if (DateTime.TryParse(raw, out final))
{
return final;
}
}
return null;
}
This is how I use the method above
DateTime? dt = dateTimeVal("2016-03-14 11:22:21.352", "yyyy-MM-dd HH:mm:ss.fff");
However, dt gives me this 3/14/2016 11:22:21 AM
How can I get the value to include the milliseconds?
DateTime final = new DateTime();
var test = DateTime.TryParseExact("2016-03-14 11:22:21.352", new string[] { "yyyy-MM-dd HH:mm:ss.fff" }, CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
This works for me.
Just take care for your fff. If you write them uppercase, the milliseconds will be supressed. Lowercase they will be parsed.
The only thing away from that I can imagine is you have used .ToString without providing any format. Then you'll get:
Are you sure you've written the providing format lowercase inside your code? Also have you used .ToString() with an output-format that shows up the milliseconds?
If you want to get the DateTime as string with milisecond, then you can use the following code;
string dateTime = dt.Value.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Hope this helps.

How do I convert a DateTime variable to return date in the 'mm/dd/yy' format

private DateTime OrderDate;
OrderDate = Convert.ToDateTime("05/20/15")
How do I assign the above OrderDate variable a value of 05/20/15.
I tried using Convert.ToDateTime, but it seems to work for yyyy format but not yy.
You will want to create a new date time object and assign it to the property.
OrderDate = new DateTime(2015, 5, 20);
To assign it, you would use OrderDate = new DateTime(2015, 5, 20);
When displaying the value the .Net Framework will use the local culture or your machine.
If you want to use a different display format, (without changing the culture) you can use String.Format("{0:MM/dd/yy}", OrderDate)
You can't, Unless you change the date string to the correct format, it cannot guess which millennium you are reffering.
or you can take each part of the date sepretly and pass it in the constructor:
OrderDate = new DateTime(2015, 5, 20);
You can use DateTime.ParseExact to achieve this
DateTime OrderDate = DateTime.ParseExact("05/20/15", "MM/dd/yy", CultureInfo.InvariantCulture);
I would use DateTime.TryParseExact:
DateTime time;
if (DateTime.TryParseExact("05/20/15", "MM/dd/yy", System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out time))
{
do something ...
}
Lots of info about converting/formatting dates you can find here:
https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/8kb3ddd4%28v=vs.110%29.aspx
I guess in particular you need this example:
MSDN snippet:
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.

Get only the Date without Time from DateTime

i came across a situation that, i need to get only the Date out from DateTime.
i am having a DateTime? StartDate property (Nullable) used to hold the date value
i tried below,
var d = Convert.ToDateTime(StartDate).Date;
but its returning me d as eg. 6/22/2006 12:00:00AM
after doing var d = Convert.ToDateTime(StartDate).Date.ToString("d");
i'm able to get d as 6/22/2006..but i dont want to convert my DateTime? to String
is their any way to get only the Date without using the ToString("d")?
Use the Date property to get the Date component of DateTime instance:
DateTime dateTimeNow = DateTime.Now;
DateTime datePartOnly = dateTimeNow.Date; // Return 00/00/0000 00:00:00
With this approach, Date property will return the date at midnight. So the time part will be 00:00:00 in this case.
There are couple of alternate ways to get the just the Date part, but the return type of it will be a string:
1.) Using .ToString(string? format) where format can be standard or custom format string
string dateOnlyString = dateTimeNow.ToString("dd/MM/yyyy");
//Can also use .ToString("dd-MM-yyyy");
2.) Using .ToShortDateString() to return a culture sensitive date string
string dateOnlyString = dateTimeNow.ToShortDateString();
//Returns M/d/yyyy for "en-US" culture
//Returns yyyy/M/d for "ja-JP" culture
Reference: here.
try this:
string x = DateTime.Now.ToShortDateString().
this will get the date dd/mm/yy given to the string x.
I think you question is sort of... moot.
You ask for a date without a time, but get a DateTime, which has both. I really don't think that should be a problem in most cases though:
If you create a DateTime with a certain date, and compare it to another date, and both of these have their time set to midnight, your comparisons will be valid and correct. Eg:
var yesterday = new DateTime(2014, 3, 10);
var today = new DateTime(2014, 3, 11);
var tomorrow = new DateTime(2014, 3, 12);
Comparing and sorting these will work as you expect, and so will the following:
if(today == DateTime.Today){
Console.WriteLine("Today is the day!");
}
In other words, you should be perfectly fine just pretending like the time-part does not exist.
Also, as you touched upon yourself in the OP, you can use the property Date if you want to make sure to avoid any time-component:
// Note the addition of hours, minutes and seconds:
var today = new DateTime(2014, 3, 11, 14, 35, 33);
if(today == DateTime.Today){
Console.WriteLine("This never happened...");
}
if(today.Date == DateTime.Today){
Console.WriteLine("...But today is still the day!");
}
In C# 10 you can use DateOnly.
DateOnly date = DateOnly.FromDateTime(DateTime.Now);
A DateTime does have both a date and a time. You can decide with yourself that in a specific property you well never use the date part. It will just be 12:00 AM, but you won't use it.
In some situations it can be useful to write your own type that can never hold a time-of-day component. Here is a start:
struct Date : IFormattable
{
readonly DateTime value;
public Date(DateTime dateAndTime)
{
value = dateAndTime.Date;
}
public string ToString(string format, IFormatProvider formatProvider)
{
return value.ToString(format ?? "d", formatProvider);
}
public string ToString(string format)
{
return ToString(format, null);
}
public string ToString(IFormatProvider formatProvider)
{
return ToString(null, formatProvider);
}
public override string ToString()
{
return ToString(null, null);
}
public static implicit operator DateTime(Date date)
{
return date.value;
}
}
The field value does hold the 12 AM thing, but it is private and is not seen from the outside. The overloads of ToString() make sure that unless something else is requested, the Date is written out with the short date format of the current culture.

String was not recognized as a valid DateTime

I want to add a date in session (date1) like this:
Session["DateLesson"] = date1.ToString("dd.MM.yyyy");
Now from the session I want take this value:
var asd = Session["DateLesson"];
/*asd = "20.04.2012"*/
var datelesson = DateTime.Parse((string) asd);
And it gives me this exception:
FormatException not recognized as a valid DateTime
A period is not a valid/standard separator character in most locales. You'll need to use DateTime.ParseExact() in combination with a format string to tell the function how to read it. More importantly, if reading it back to a datetime is your main goal, why not just put the datetime in the session as is? That seems way more efficient, easier, and more maintainable to me.
Why persist your date as a string?
You could simply store it like this:
Session["DateLesson"] = date1;
And then retrieve it like this:
var datelesson = (DateTime)Session["DateLesson"];
string value = "20.04.2012";
DateTime datetime = DateTime.ParseExact(value, "dd.MM.yyyy", null);
This will return 4/20/2012 12:00:00:00 AM
Don't keep value as a string but as an object of the initial type:
public DateTime? DateLesson
{
get
{
DateTime? dateTime = Session["DateLesson"] as DateTime?;
if (dateTime.HasValue) // not null
{
// use dateTime.Value
}
}
set
{
Session["DateLesson"] = value;
}
}

Categories