Format a string to display the Date correctly - c#

I need help converting this string --> 20090727 10:16:36:643 to --> 07/27/2009 10:16:36
The original date and time are being returned by the SynchronizationAgent.LastUpdated() function, which returns a String in the above format.
Original question:preserved for reference
I have this -->
HUD.LastSyncDate = mergeSubscription.SynchronizationAgent.LastUpdatedTime;
Which is setting a property that looks like this -->
public static string LastSyncDate
{
get { return _lastSyncDate; }
set
{
_lastSyncDate = String.Format(CultureInfo.InvariantCulture,"{0:G}", value);
}
}
Unfortunately, with or without the String.Format the date that is displayed looks like this --> 20090727 10:16:36:643
I have tried multiple variations to Format it the way I want. What am I missing?
Based on the below suggestions(Mostly Joel's), I implemented the suggested changes but I am still getting a "String is not a valid DateTime error"
I also tried implementing this -->
HUD.LastSyncDate = DateTime.ParseExact(mergeSubscription.SynchronizationAgent.LastUpdatedTime,"yyyyMMdd HH:mm:ss:fff",CultureInfo.InvariantCulture);
but still nothing.

HUD.LastSyncDate = DateTime.Parse(mergeSubscription.SynchronizationAgent.LastUpdatedTime).ToString("MM/dd/yyyy")
You can put any format string you want there. But it sounds like what you really want is something more like this:
private static DateTime _lastSyncDate;
public static DateTime LastSyncDate
{
get { return _lastSyncDate; }
set { _lastSyncDate = value;}
}
public static string LastSyncDateString
{
get { return LastSyncDate.ToString("MM/dd/yyyy"); }
}
Keep it as a datetime in the background and just use the string property for display.

It appears to me that LastUpdatedTime is actually a string (since you can do the assignment) not a DateTime. In that case, the format applied won't do anything. You'll want to parse the LastUpdatedTime into a DateTime then reformat into the format that you want before assigning it to your string.
DateTime lastUpdated = DateTime.Parse( mergeSubscription.SynchronizationAgent.LastUpdatedTime );
HUD.LastSyncDate = string.Format( "{0:G}", lastUpdated );
public static string LastSyncDate { get; set; }
Note that you may need to use ParseExact instead.
DateTime lastUpdated = DateTime.ParseExact( "yyyyMMdd HH:mm:ss:fff",
...,
CultureInfo.InvariantCulture );

What do you want to do? You get a string, pass it to String.Format() and store it in a string field. Do you want to reformat the string? In this case you have to parse the string back to DateTime and format this value again.
DateTime dateTime;
if (DateTime.TryParse(value, out dateTime))
{
lastSyncDate = String.Format(CultureInfo.InvariantCulture,"{0:G}", dateTime);
}
else
{
HandleInvalidInput(value);
}

Related

Parse custom JSON string to DateTime Convert in API

My Question is similar to this one (The JSON value could not be converted to System.DateTime), where I am trying to convert an input string to an DateTime. The difference, however, is that the input string cannot be changed. I have no choice in it.
[HttpPut("PutBodyToFoodChain")]
public async Task<IActionResult> PutBodyToFoodChain([FromBody] TxMSAGrading body)
{ ... }
What I've tried:
[JsonConverter(typeof(DateFormatConverter), "MM/dd/yyyy hh:mm:ss")]
public DateTime KillDate { get; set; }
Error:
The JSON value could not be converted to System.DateTime
Input String:
{"GradeDate": "08/24/2020 01:36:00", "KillDate" : "08/24/2020 00:00:00", ... }
Additional Information:
I cannot change the model. So it will always be parsed in to be converted to a Date-Time.
There are 500+ fields in the model. I can't explicitly convert every Date-time field.
DateTime fields will always have the same format.
One idea is to defer parsing until after the raw string is captured in your model. This allows deserialization to succeed more reliably and for you to have control over the parsing. For example, an updated model:
public string KillDate { get; set; }
public DateTime KillDateValue => DateTime.TryParse(KillDate, out DateTime parsed) ? parsed : DateTime.MinValue;
public bool KillDateParsed => KillDateValue != DateTime.MinValue;
If parsing succeeds, KillDateParsed will be true and you'll have the parsed value in KillDateValue. DateTime.TryParse can also be provided a specific pattern to match.

Converting value type inside class property

Hi I am having a simple problem, I am trying to convert (value is DateTime and i want to convert it to string) value type inside class to another type, so far i have tried:
private string timestamp;
public string timestamp
{
get => timestamp;
set
{
if (value != timestamp)
{
timestamp = (DateTime)value.ToString("dd'/'MM'/'yyyy HH':'mm':'ss.fff");
}
}
}
But with no luck. Is there a solution for this??
You are converting a string to a string using ToString with a formatter that you would expect on a DateTime, and then you're casting it to a DateTime that has to be assigned to a string.
Obviously, this cannot work.
If you are trying to validate if the new property-value (Value) can be considered as a valid string, then use DateTime.TryParseExact to verify if the given string is a valid DateTime. If so, assign the string to the backing field of the property.
set
{
if (value != timestamp && DateTime.TryParseExact(value,
"dd'/'MM'/'yyyy HH':'mm':'ss.fff",
CultureInfo.CurrentCulture,
DateTimeStyles.None, DateTime out d )
{
timestamp = value;
}
}
You will have to fiddle around a bit with the arguments of the TryParseExact method to see what works in your scenario.

Set format of data for serializer in WCF

I have something like:
[DataContract]
DateTime date;
However, I have specific format of my date: 20170403. How to force WCF serializer to serialize such format ? At this moment it returns validation error. How to do it ?
DataContractSerializer is going to follow the expected XML date format rules for dates, so if the other end isn't expecting that: you simply can't use a date. You'll have to expose it as a string instead:
public DateTime Date {get;set;} // note no serialization attribs
[DataMember(Name="date")]
public string DateString {
get { return Date.WhateverFormattingCodeYouWantHere(); }
set { Date = value.WhateverParsingCodeYouWantHere(); }
}
[Serializable]
[DataContract(IsReference = true)]
public className{
[DataMember]
DateTime date;
}
Hope this will help

Storing Utc Time in Getter/Setter Property

Currently, I am storing theDateTime with the DeliveryDate getter/setter. However, I'm having issues storing this in UTC time. I've done some research on this and tried DateTimeKind.Utc but can't get that to work correctly. How can I get DeliveryDate to store the DateTime in UTC time?
My Code:
public partial class shippingInfo
{
public System.Guid EmailConfirmationId {get; set; }
public Nullable<System.DateTime> DeliveryDate {get; set; }
}
Update: Added Implementation:
DeliveryExpirationRepository.Add(new DeliveryPendingConfirmation
{
EmailConfirmationId = newGuid,
DeliveryDate = DateTime.Now.AddHours(48),
});
To make a DateTime store a UTC value, you must assign it a UTC value. Note the use of DateTime.UtcNow instead of DateTime.Now:
DeliveryExpirationRepository.Add(new DeliveryPendingConfirmation
{
EmailConfirmationId = newGuid,
DeliveryDate = DateTime.UtcNow.AddHours(48),
});
The DateTime.UtcNow documentation says:
Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
The DateTime.Now documentation says:
Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.
You might want to use DateTimeOffset instead. It always stores an absolute point in time, unambiguously.
You can add a code to the setter method to check if value is not in UTC and convert this value to UTC:
public class shippingInfo {
public System.Guid EmailConfirmationId { get; set; }
private Nullable<System.DateTime> fDeliveryDate;
public Nullable<System.DateTime> DeliveryDate {
get { return fDeliveryDate; }
set {
if (value.HasValue && value.Value.Kind != DateTimeKind.Utc) {
fDeliveryDate = value.Value.ToUniversalTime();
}
else {
fDeliveryDate = value;
}
}
}
}
In this case, you don't need to care how a value of this property is set. Or you can use the DateTime.ToUniversalTime method to convert any date to UTC where you set a value of the property.

DataMember Property with Custom Get?

I'm going by this tutorial and trying to figure out how to have a DataMember without an auto property. Basically I have a field is a date time in epoch format and I want the property to be a DateTime so I'm trying to do the conversion in the property's get. I'm not sure how to format this exactly.
Since Code was requested please look at the following. :
// The date looks like this in the JSON
"someEpochDateTime": 1428785212000,
// I thought I could work around it using the following code, however
// I get a warning saying someEpochDateTime is never set.
[DataMember(Name = "someEpochDateTime")]
private long someEpochDateTime;
public DateTime test
{
get { return DateTimeConverter.FromUnixTime(someEpochDateTime); }
}
Using FromUnixTime
like this you can create datereturn property this will return date
[DataContract]
public class Mycontractclass
{
// Apply the DataMemberAttribute to the property.
[DataMember]
public DateTime datereturn
{
get
{
return this.dateCreated.HasValue
? this.dateCreated.Value
: DateTime.Now;
}
set { this.dateCreated = value; }
}
private DateTime? dateCreated = null;
}
Apparently my last edit actually works as a solution, I just get a compiler warning for some reason.
[DataMember(Name = "someEpochDateTime")]
private long someEpochDateTime;
public DateTime test
{
get { return DateTimeConverter.FromUnixTime(someEpochDateTime); }
}

Categories