Asp.Net MVC web API forcing UTC conversion on dateTime - c#

On my API(ASP.Net, .NET Framework 4.5), I need to return datetime in this format: 2020-06-19T13:30:44+00:00
So I created a new converter
public class JsonDateFormatConverter : IsoDateTimeConverter
{
public JsonDateFormatConverter(string format)
{
DateTimeFormat = format;
}
}
And decorated my models:
[JsonConverter(typeof(JsonDateFormatConverter), "yyyy-MM-ddTHH:mm:sszzz")]
public DateTime? StartDate{ get; set; }
But instead of returning the for examle "2020-03-07T00:00:00+01:00" im getting "2020-03-06T23:00:00Z"
So it seems that everything is being converted to UTC before serialization to JSON.
I tried setting this in WebApiConfing
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
But that did not help.
Also tried setting the dateTime kind like this:
[JsonConverter(typeof(JsonDateFormatConverter), "yyyy-MM-ddTHH:mm:sszzz")]
public DateTime? StartDate
{
get => startDate;
set
{
if (value != null)
startDate= DateTime.SpecifyKind(value.Value, DateTimeKind.Local);
else
startDate= value;
}
}
private DateTime? startDate;
Also didnt help.

Related

Why is the date returned as "0001-01-01" when calling a web service?

I have a very peculiar problem.
I have this code:
DT_PMNotificationRequestRecords request = new DT_PMNotificationRequestRecords();
request.NOTIF_DATE = DateTime.ParseExact(txtNotifData.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
request.REQ_START = DateTime.ParseExact(txtReqStart.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Now both Notif_DATE and REQ_START have proper date values.
But when the request object is passed to the web service that I have written using the same class as an object in array.
requestRecords = new DT_PMNotificationRequestRecords[]{request, request2};
Notif = new Notifications.SI_PMNotification_Out_SyncResponseSoapClient(bindingHttp, endPointHttp);
Notif.SI_PMNotification_Out_Sync(requestRecords);
Web service:
public DT_PMNotificationResponseRecords[] SI_PMNotification_Out_Sync(DT_PMNotificationRequestRecords[] request)
{
try
{
Here in the request object the REQ_Start date is returned as "0001-01-01" but notif_date is correct, e.g. 10-10-2019.
In class the fields are defined like this:
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="date", Order=6)]
public System.DateTime NOTIF_DATE
{
get { return this.nOTIF_DATEField; }
set {
this.nOTIF_DATEField = value;
this.RaisePropertyChanged("NOTIF_DATE");
}
}
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, DataType="date", Order=10)]
public System.DateTime REQ_START
{
get { return this.rEQ_STARTField; }
set {
this.rEQ_STARTField = value;
this.RaisePropertyChanged("REQ_START");
}
}

DateTime? AddDays Extension Method

I want to write an extension method that adds one day to a Nullable DateTime, but modifies the date itself.
I want to use it as follows:
someDate.AddOneDay();
This directly changes the value of someDate.
The code I initially wrote was:
public static DateTime? AddOneDay(this DateTime? date)
{
if (date.HasValue)
{
date.Value = date.Value.AddDays(1);
}
return null;
}
but this doesn't work since the reference is changed thus calling it this way
won't change the value of someDate.
Is there a way to achieve this and avoid code like:
someDate = someDate.AddOneDay();
Also I was thinking for some setter of the DateTime properties, but they don't have any..
public int Day { get; }
public int Month { get; }
public int Year { get; }
You can't DateTime is immutable, and should stay that way.
Just do:
someDate = someDate.AddOneDay();
And if you want to be more specific, you could rename your function to:
DateTime? someDate = someDate.AddOneDayOrDefault();
old school %)
public static void AddOneDay(ref DateTime date)
{
if (date != null) date = date.AddDays(1);
}
usage:
DateTime date = DateTime.Now;
AddOneDay(ref date);
UPD
one line version of method:
public static void AddOneDay(ref DateTime date) { date = date.AddDays(1); }
C# does support a similar feature, even for mutable values, which is the use of += on nullable values:
DateTime? date = GetDate();
var oneDay = TimeSpan.FromDays(1);
date += oneDay;

DataContractJsonSerializer Date Serialization

Is there a way to change how the DataContractJsonSerializer serializes dates?
Currently, it'll convert a date to something like:
{
"date": "/Date(1260597600000-0600)/"
}
I want to convert it into human readable date format.
I am building a RestApi using openrasta framework. Can i write OperationInterceptors which will at some stage before serialization/deserialization convert JSON datetime format to something which is human readable?Or is there any other way to do it?
Use DataContractJsonSerializer constructor to pass your serialization settings:
var s = new DataContractJsonSerializer(
typeof(YourTypeToSerialize),
new DataContractJsonSerializerSettings
{
DateTimeFormat = new DateTimeFormat("yyyy-MM-dd'T'HH:mm:ss")
}
);
Finally i have handled this issue as below(c#)
[DataMember]
public string Date { get; set; }
[IgnoreDataMember]
public DateTime? DateForInternalUse { get; set; }
[OnSerializing]
public void OnSerializing(StreamingContext context)
{
Date = (DateForInternalUse != null) ? ((DateTime)DateForInternalUse).ToString(DateTimeFormatForSerialization) : null;
}
[OnDeserialized]
public void OnDeserialized(StreamingContext context)
{
try
{
DateForInternalUse = !String.IsNullOrEmpty(Date) ? DateTime.ParseExact(Date, DateTimeFormats, null, DateTimeStyles.None) : (DateTime?)null;
}
catch (FormatException)
{
DateForInternalUse = null;
}
}
In this case we can specify the formats which we want to support which i have kept inside web.config
<add key="DateTimePattern" value="yyyy-MM-dd,yyyy-MM-dd hh:mm:ss zzz,yyyy-MM-dd hh:mm:ss" />
Let me know for further clarifications.

webservice DateTime unexpected value?

When I use the system.datetime as my datamember it returns a strange format in my datagridview.
My Datamembers looks like this:
[DataMember(Name = "TimeAdded")]
public DateTime TimeAdded;
And my AddStudent looks like this:
public void AddStudent(Student student)
{
student.StudentID = (++eCount).ToString();
student.TimeAdded = DateTime.Now; // not important more so the method to get the correct format
students.Add(student);
}
The output I get is 2012-04-12T03:10:42.8138255+01:00 is there a way to fix this?
I think you want:
student.TimeAdded = DateTime.Now;
Right now you're just converting a null time to local time.
Assuming you are referring to the fact that your dates are set to default(DateTime), then you want yamen's answer, if you don't like the format the DateTime is showing, then add another property onto Student that uses a standard DateTime format string like so.
public class Student
{
// existing date, don't expose this
public DateTime TimeAdded;
// expose this instead
[DataMember(Name = "TimeAddedString")]
public string TimeAddedString
{
//show as "Monday, January 01, 0001 12:00 AM"
get { return this.TimeAdded.ToString("f"); }
}
}
public class Student
{
public string TimeAddedString
{
get
{
return this.TimeAdded.ToString("dd/MM/yyyy hh:mm:ss");
// your desired format can goes here
}
}
}
public void AddStudent(Student student)
{
student.StudentID = (++eCount).ToString();
student.TimeAdded = DateTime.Now; // or your desired datetime
students.Add(student);
}
If you are converting incoming student time added you need to re-assign it:
public void AddStudent(Student student)
{
student.StudentID = (++eCount).ToString();
student.TimeAdded = student.TimeAdded.ToLocalTime();
students.Add(student);
}

How to remove time portion of date in C# in DateTime object only?

I need to remove time portion of date time or probably have the date in following format in object form not in the form of string.
06/26/2009 00:00:00:000
I can not use any string conversion methods as I need the date in object form.
I tried first converting the DateTime to a string, remove the time specific date from it, but it adds 12:00:00 AM as soon as I convert it back to DateTime object back again.
Use the Date property:
var dateAndTime = DateTime.Now;
var date = dateAndTime.Date;
The date variable will contain the date, the time part will be 00:00:00.
You can use format strings to give the output string the format you like.
DateTime dateAndTime = DateTime.Now;
Console.WriteLine(dateAndTime.ToString("dd/MM/yyyy")); // Will give you smth like 25/05/2011
Read more about Custom date and time format strings.
Use the method ToShortDateString. See the documentation http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx
var dateTimeNow = DateTime.Now; // Return 00/00/0000 00:00:00
var dateOnlyString = dateTimeNow.ToShortDateString(); //Return 00/00/0000
Have a look at the DateTime.Date property.
Gets the date component of this instance.
The Date property will return the date at midnight.
One option could be to get the individual values (day/month/year) separately and store it in the type you want.
var dateAndTime = DateTime.Now;
int year = dateAndTime.Year;
int month = dateAndTime.Month;
int day = dateAndTime.Day;
string.Format("{0}/{1}/{2}", month, day, year);
None of the above answers solved my problem on winforms.
the easiest way to reach ONLY date is the simple function in Datetime:
DateTime dt = DateTime.now;
String BirthDate = dt.ToShortDateString();
You will only have date in Birthday string .
Try to make your own Structure for that. DateTime object will have date and time both
You can't. A DateTime in .NET always have a time, defaulting to 00:00:00:000. The Date property of a DateTime is also a DateTime (!), thus having a time defaulting to 00:00:00:000 as well.
This is a shortage in the .NET Framework, and it could be argued that DateTime in .NET violates the Single Responsibility Principle.
The easiest way is something like this and it will return only the date:
var date = DateTime.Now.ToShortDateString();
Here is another method using String.Format
DateTime todaysDate = DateTime.UtcNow;
string dateString = String.Format("{0:dd/MM/yyyy}", todaysDate);
Console.WriteLine("Date with Time: "+ todaysDate.ToString());
Console.WriteLine("Date Only : " + dateString);
Output:
Date with Time: 9/4/2016 11:42:16 AM
Date Only : 04/09/2016
This also works if the Date Time is stored in database.
For More Date and Time formatting check these links:
Reference 1
Reference 2
Hope helps.
DateTime.Date
var newDate = DateTime.Now; //newDate.Date property is date portion of DateTime
This way of get only date without time
DateTime date = DateTime.Now;
string Strdateonly = date.ToString("d");
Output = 5/16/2015
Use date.ToShortDateString() to get the date without the time component
var date = DateTime.Now
var shortDate = date.ToShortDateString() //will give you 16/01/2019
use date.ToString() to customize the format of the date
var date = DateTime.Now
var shortDate = date.ToString('dd-MMM-yyyy') //will give you 16-Jan-2019
Since .NET 6 / C# 10 you can do this:
var dateOnly = DateOnly.FromDateTime(dateTime);
I wrote a DateOnly structure. This uses a DateTime under the skin but no time parts are exposed publically:
using System;
public struct DateOnly : IComparable, IFormattable, IComparable<DateOnly>, IEquatable<DateOnly>
{
private DateTime _dateValue;
public int CompareTo(object obj)
{
if (obj == null)
{
return 1;
}
DateOnly otherDateOnly = (DateOnly)obj;
if (otherDateOnly != null)
{
return ToDateTime().CompareTo(otherDateOnly.ToDateTime());
}
else
{
throw new ArgumentException("Object is not a DateOnly");
}
}
int IComparable<DateOnly>.CompareTo(DateOnly other)
{
return this.CompareToOfT(other);
}
public int CompareToOfT(DateOnly other)
{
// If other is not a valid object reference, this instance is greater.
if (other == new DateOnly())
{
return 1;
}
return this.ToDateTime().CompareTo(other.ToDateTime());
}
bool IEquatable<DateOnly>.Equals(DateOnly other)
{
return this.EqualsOfT(other);
}
public bool EqualsOfT(DateOnly other)
{
if (other == new DateOnly())
{
return false;
}
if (this.Year == other.Year && this.Month == other.Month && this.Day == other.Day)
{
return true;
}
else
{
return false;
}
}
public static DateOnly Now()
{
return new DateOnly(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
}
public static bool TryParse(string s, ref DateOnly result)
{
DateTime dateValue = default(DateTime);
if (DateTime.TryParse(s, out dateValue))
{
result = new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
return true;
}
else
{
return false;
}
}
public static DateOnly Parse(string s)
{
DateTime dateValue = default(DateTime);
dateValue = DateTime.Parse(s);
return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
}
public static DateOnly ParseExact(string s, string format)
{
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dateValue = default(DateTime);
dateValue = DateTime.ParseExact(s, format, provider);
return new DateOnly(dateValue.Year, dateValue.Month, dateValue.Day);
}
public DateOnly(int yearValue, int monthValue, int dayValue) : this()
{
Year = yearValue;
Month = monthValue;
Day = dayValue;
}
public DateOnly AddDays(double value)
{
DateTime d = new DateTime(this.Year, this.Month, this.Day);
d = d.AddDays(value);
return new DateOnly(d.Year, d.Month, d.Day);
}
public DateOnly AddMonths(int months)
{
DateTime d = new DateTime(this.Year, this.Month, this.Day);
d = d.AddMonths(months);
return new DateOnly(d.Year, d.Month, d.Day);
}
public DateOnly AddYears(int years)
{
DateTime d = new DateTime(this.Year, this.Month, this.Day);
d = d.AddYears(years);
return new DateOnly(d.Year, d.Month, d.Day);
}
public DayOfWeek DayOfWeek
{
get
{
return _dateValue.DayOfWeek;
}
}
public DateTime ToDateTime()
{
return _dateValue;
}
public int Year
{
get
{
return _dateValue.Year;
}
set
{
_dateValue = new DateTime(value, Month, Day);
}
}
public int Month
{
get
{
return _dateValue.Month;
}
set
{
_dateValue = new DateTime(Year, value, Day);
}
}
public int Day
{
get
{
return _dateValue.Day;
}
set
{
_dateValue = new DateTime(Year, Month, value);
}
}
public static bool operator == (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() == aDateOnly2.ToDateTime());
}
public static bool operator != (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() != aDateOnly2.ToDateTime());
}
public static bool operator > (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() > aDateOnly2.ToDateTime());
}
public static bool operator < (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() < aDateOnly2.ToDateTime());
}
public static bool operator >= (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() >= aDateOnly2.ToDateTime());
}
public static bool operator <= (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() <= aDateOnly2.ToDateTime());
}
public static TimeSpan operator - (DateOnly aDateOnly1, DateOnly aDateOnly2)
{
return (aDateOnly1.ToDateTime() - aDateOnly2.ToDateTime());
}
public override string ToString()
{
return _dateValue.ToShortDateString();
}
public string ToString(string format)
{
return _dateValue.ToString(format);
}
public string ToString(string fmt, IFormatProvider provider)
{
return string.Format("{0:" + fmt + "}", _dateValue);
}
public string ToShortDateString()
{
return _dateValue.ToShortDateString();
}
public string ToDbFormat()
{
return string.Format("{0:yyyy-MM-dd}", _dateValue);
}
}
This is converted from VB.NET, so apologies if some conversions are not 100%
I'm surprised no one has mentioned DateTime.Today
var date = DateTime.Today;
// {7/1/2014 12:00:00 AM}
See MSDN
If you are converting it to string, you can easily do it like this.
I'm taking date as your DateTime object.
date.ToString("d");
This will give you only the date.
You Can Try This for the Only Date From the Datetime
String.Format("{0:d/M/YYYY}",dt);
Where dt is the DateTime
Came across this post when trying to solve the original Q.
I am using Asp.Net and after some research I have found when you are binding to the value of the date in code behind, you can drop the time so it will not display on screen.
C#:
DateTime Today = DateTime.Now;
aspx:
<%: this.Today.ToShortDateString() %>
use
DateTime.Now.ToString("dd-MM-yyyy");
I know this is an old post with many answers, but I haven't seen this way of removing the time portion. Suppose you have a DateTime variable called myDate, with the date with time part. You can create a new DateTime object from it, without the time part, using this constructor:
public DateTime(int year, int month, int day);
Like this:
myDate = new DateTime(myDate.Year, myDate.Month, myDate.Day);
This way you create a new DateTime object based on the old one, with 00:00:00 as time part.
You can use this simple code below.
Code: DateTime.Now.ToShortDateString();
Ex.
Console.WriteLine(DateTime.Now.ToShortDateString());
This is for C#10 and above where now a DateOnly and TimeOnly format is available. Using below format, you can extract DateOnly from a DateTime format.
DateOnly myDateNoTime = DateOnly.FromDateTime(DateTime.Now);
string dt = myCalender.SelectedDate.ToString();
string date = dt.Remove(10);
displayDate.Content = date;
If you take date from calender, with this we also get time. Which is not required all time. Using this we can remove time from date.
in my experience none of the said solutions worked, maybe because I wanted to remove the time from extracted date from database, but the code below worked fine:
var date = target_date.Value.ToString("dd/MM/yyyy");
Declare the variable as a string.
example :
public string dateOfBirth ;
then assign a value like :
dateOfBirth = ((DateTime)(datetimevaluefromDB)).ToShortDateString();
This could be simply done this way:
var dateOnly = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day)
Create a struct that holds only the properties you want. Then an extension method to easily get that struct from an instance of DateTime.
public struct DateOnly
{
public int Day { get; set; }
public int Month { get; set; }
public int Year { get; set; }
}
public static class DateOnlyExtensions
{
public static DateOnly GetDateOnly(this DateTime dt)
{
return new DateOnly
{
Day = dt.Day,
Month = dt.Month,
Year = dt.Year
};
}
}
Usage
DateTime dt = DateTime.Now;
DateOnly result = dt.GetDateOnly();
To get only the date portion use the ToString() method,
example:
DateTime.Now.Date.ToString("dd/MM/yyyy")
Note:
The mm in the dd/MM/yyyy format must be capitalized
Add Date property to the DateTime variable
var dateTime = DateTime.Now
var onlyDate = dateTime.Date
Or You can use DataType annotation as well.
[DataType(DataType.Date)]
public DateTime dateTime {get; set;}
The DataType annotation is inside the System.ComponentModel.DataAnnotations namespace.

Categories

Resources