Parsing a DateTime value in the SyndicationFeed - c#

I'm using below code for parsing an atom feed:
using(var reader = new MyXmlReader("http://tutsplus.com/courses.atom")) {
var doc = SyndicationFeed.Load(reader);
var newFeed = new AtomFeed {
Id = doc.Id,
Title = doc.Title.Text,
Url = url,
UpdateDate = DateTime.Now
};
XNamespace dc = "http://www.w3.org/2005/Atom";
newFeed.AtomEntries = (from entry in doc.Items
select new AtomEntry {
Id = entry.Id,
Links = entry.Links,
Title = entry.Title.Text,
Content = entry.Content.ToString(),
PublishDate = entry.PublishDate.DateTime,
UpdatedDate = entry.LastUpdatedTime.DateTime,
Authors = entry.Authors
}).ToList();
}
Seems that a string was not recognized as a valid DateTime in my feed. I'm also aware (+) that The SyndicationFeed.Load method expects to receive feeds that are in standard format like this: Mon, 05 Oct 2015 08:00:06 GMT. So I created my custom XML reader that recognizes different date formats. But still have same error!
Any idea?

When I tried it, with your linked custom XML reader, I also got this error when it came to parsing the "published" and "updated" dates. Looking at the code for the Atom10FeedFormatter class, it is trying to parse dates in these formats (DateFromString method)
const string Rfc3339LocalDateTimeFormat = "yyyy-MM-ddTHH:mm:sszzz";
const string Rfc3339UTCDateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ";
http://reflector.webtropy.com/default.aspx/WCF/WCF/3#5#30729#1/untmp/Orcas/SP/ndp/cdf/src/NetFx35/System#ServiceModel#Web/System/ServiceModel/Syndication/Atom10FeedFormatter#cs/2/Atom10FeedFormatter#cs
So I changed in the MyXmlReader implementation to set that format yyyy-MM-ddTHH:mm:ssZ, then all is well with this date parsing (I also had to change in ReadStartElement the element names to set readingDate equal to true, i.e. published and updated).
public override string ReadString()
{
if (readingDate)
{
string dateString = base.ReadString();
DateTime dt;
if (!DateTime.TryParse(dateString, out dt))
dt = DateTime.ParseExact(dateString, CustomUtcDateTimeFormat, CultureInfo.InvariantCulture);
return dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture);
}
else
{
return base.ReadString();
}
}

Related

Convert dd/mm/yyyy string to yyyy-dd-mm DateTime in c#

How do I convert 13/05/2019 (dd/mm/yyyy) string to 2019-13-05 (YYYY-dd-mm) DateTime Datatype in c#,sql sever Expects YYYY-dd-mm format datatype
string dateTime = "05/13/2019";
if (animalAdoption.AdoptionId != 0)
{
AnimalsAndBirdsAdoption animalsAndBirdsAdoption = new AnimalsAndBirdsAdoption()
{
AnimalsAndBirdsId = animalAdoption.AnimalId,
DonarDetailsId = userId,
Term = model.Term,
PeriodOfAdoption = dateTime,
isActive = true,
Amount = animalAdoption.amount
};
if (context.AnimalsAndBirdsAdoptions.Any(e => e.Id == animalAdoption.AdoptionId))
{
context.AnimalsAndBirdsAdoptions.Attach(animalsAndBirdsAdoption);
}
else
{
context.AnimalsAndBirdsAdoptions.Add(animalsAndBirdsAdoption);
}
}
this out-put I get
You can do it simply using below example with using your required format:
string dateTime = "05/13/2019";
CultureInfo provider = CultureInfo.InvariantCulture;
// It throws Argument null exception
DateTime dateTime10 = DateTime.ParseExact(dateTime, "yyyy/dd/mm", provider);
string dateTime = "13/05/2019";
var splittedDateTime = dateTime.Split('/');
DateTime myDate = new DateTime(int.Parse(splittedDateTime[2]), int.Parse(splittedDateTime[1]), int.Parse(splittedDateTime[0]));
To convert a UK date string to a DateTime
public DateTime? ToDateTime(string text)
{
DateTime? returnValue = null;
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-GB");
DateTime d = new DateTime();
if(DateTime.TryParse(text, cultureInfo, System.Globalization.DateTimeStyles.None, out d))
{
returnValue = d;
}
return returnValue;
}
To convert a DateTime to string yyyy-MM-dd:
public string ToBigEndianString(DateTime? date)
{
string returnValue = null;
if(date != null)
{
returnValue = date.Value.ToString("yyyy-MM-dd");
}
return returnValue;
}
Then you can put them together:
public string ToBigEndianString(string ukDate)
{
DateTime? d = ToDateTime(ukDate);
return ToBigEndianString(d);
}
But you could pass in a DateTime to a SQL stored procedure.
https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparametercollection.addwithvalue?view=netframework-4.8
Change the datatype of PeriodOfAdoption to Type System.DateTime
and then you can initialise the property using the DateTime constructor which has many overloads.
If your string format is always in the form yyyy-dd-mm based on: '2019-13-05'
you can extract the year the month and the day, by perhaps using .Split('-') string function or if its the format: '2019/13/05' you can split on '/' e.g. .Split('/').
Then you can create your DateTime object using the constructor like so (you can view them here https://learn.microsoft.com/en-us/dotnet/api/system.datetime.-ctor?view=netframework-4.8):
constructor:
public DateTime (int year, int month, int day);
initialisation:
PeriodOfAdoption = new DateTime(2019, 5, 13)
so putting it together:
var dateTime = '2019/13/05';
var dateParts = dateTime.Split('/');
PeriodOfAdoption = new DateTime(Int32.parse(dateParts[0]), Int32.parse(dateParts[1]), Int32.parse(dateParts[2]));
If you need a string in the c# side, this is very simple in C# and there are many examples online

C# If else program not recognizing the if statement and only taking the else

Hi i have the following code, the problem i am facing is no matter if the folder exists it still continues to send the email instead of ignoring to send it.
What can i change to get this working.
static void Main(string[] args)
{
string yesterdaydate = DateTime.Now.AddDays(-1).ToString("yyyy-mm-dd");
string[] SplitDate = yesterdaydate.Split('-');
string year = SplitDate[0];
string month = SplitDate[1];
string day = SplitDate[2];
string path = Path.Combine("C:\\Users\\ales\\Desktop\\test", year, month, day);
if (Directory.Exists(path))
{
//do nothing
}
else
{
string fromAddress = "noreply#arm.com";
string toAddress = "alese#arm.com";
string subject = "error";
string body = "failed to sync";
krysalis_email.EmailClient email = new krysalis_email.EmailClient();
krysalis_email.EmailClient.EmailResponse emailResponse = email.sendBasicMail(new object[] {toAddress}, fromAddress, subject, body, false, "smtp.za.arm.com",
new string[] {"", ""}, false, null);
if (emailResponse != null)
{
}
}
}
The problem is in your date format to string. You are using mm which is minutes. Use MM to get month. Keep in mind that MM format will give you month with leading zero, for example 08
If you want to use string splitting, then change the code to
string yesterdaydate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
But as others pointing, the better way to get values is to use DateTime instead of parsing string. Here is an example:
DateTime yesterdaydate = DateTime.Now.AddDays(-1);
string year = yesterdaydate.Year.ToString();
string month = yesterdaydate.Month.ToString("D2");//D2 to format number to be zero-padded
string day = yesterdaydate.Day.ToString("D2");
string path = Path.Combine("C:\\Users\\ales\\Desktop\\test", year, month, day);

Convert string to DateTime Format - wrong format

I really cannot make sense of why this does not want to work. I get an exception:
String was not recognized as a valid DateTime.
I am reading the string date from a file and looks like this 2/27/2014 10:10:55
This method receives the filename and extrapolates the data I need (latitude, longitude, date)
public void ReadCsvFile(string filename)
{
var reader = new StreamReader(File.OpenRead(filename));
gpsDataList = new List<GpsFileClass>();
while(!reader.EndOfStream){
var line = reader.ReadLine();
var values = line.Split(',');
if(values[2].Contains("A")){
values[2] = values[2].Substring(0,values[2].IndexOf("A"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
if(values[2].Contains("P")){
values[2] = values[2].Substring(0, values[2].IndexOf("P"));
values[2].Replace("\"", "");
values[2] = values[2].Trim();
}
gpsDataList.Add(new GpsFileClass(Convert.ToDouble(values[0]), Convert.ToDouble(values[1]), Convert.ToString(values[2])));
}
}
Once the I have the file data in a List<> I want to do some date comparisons and calculations. But first; I try to convert the string data containing date information to datetime like this:
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
As you can see even ParseExact throws the same exception, I tried it (hence commented it out).
There are a lot solutions for this kind of problem but non seem to work on mine. I get that DateTime by default uses en-US calture. But When I even when I change the culture to "af-ZA" I get the same exception.
Please help.
I don't believe it; The variable that holds the size of the List<> was going out of range (check line 3 of code below) but for some reason it did not throw an "out of range exception".
public void SaveFrameGpsCoordinate()
{
int listSize = gpsDataList.Count - 1;
DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo();
dateTimeFormatInfo.ShortDatePattern = "dd-MM-yyyy HH:mm:ss";
dateTimeFormatInfo.DateSeparator = "/";
//DateTime tempDateA = DateTime.ParseExact(gpsDataList[0].timeCaptured, "dd/MM/yyyy HH:mm:ss",null);
//DateTime tempDateB = DateTime.ParseExact(gpsDataList[lastRecordData].timeCaptured, "dd/MM/yyyy HH:mm:ss", null);
DateTime tempDateA = Convert.ToDateTime(gpsDataList[0].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
DateTime tempDateB = Convert.ToDateTime(gpsDataList[lastRecordData].timeCaptured.Replace("\"", ""), System.Globalization.CultureInfo.GetCultureInfo("hi-IN").DateTimeFormat);
}
You can use the ParseExact method
var dateTime = DateTime.ParseExact("2/27/2014 10:10:55",
"M/d/yyyy h:m:s", CultureInfo.InvariantCulture);
'dd' expects a 2 digit date. You probably want to use 'd' instead.
Similarly 'MM' expects a 2 digit month - again you probably want to use 'M' instead.
Source: http://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx

DateTime class common error displayed again

I run into a little common problem with datetime class that I have no idea how to resolve.
I don't know what the error is but I see the troubleshooting tips are displayed as
When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object. Make sure your method arguments are in the right format.
Here is the piece of code I extract from my program,
public IEnumerable<CONTACT_INFO> GetContactInfo(string tableName)
{
DataTable dt = GetUserInfo(tableName);
List<CONTACT_INFO> lst = new List<CONTACT_INFO>();
foreach (DataRow row in dt.Rows)
{
string sDate = "";
if(!string.IsNullOrEmpty(row["birthday"].ToString()))
{
sDate = row["birthday"].ToString();
}
string format = "yyyyMMdd";
System.Globalization.CultureInfo provider =CultureInfo.InvariantCulture;
string datetime = DateTime.Now.ToShortDateString();
if (!string.IsNullOrEmpty(sDate))
{
datetime = DateTime.ParseExact(sDate, format, provider).ToShortDateString();
}
if (row["companyname"].ToString().CompareTo("companylogo") != 0)
{
string profile_time = row["profile_timestamp"].ToString();
if (!string.IsNullOrEmpty(profile_time))
{
CSTimeZone time = new CSTimeZone();
profile_time = time.FromUnix(Convert.ToDouble(profile_time)).ToShortDateString()+" "+
time.FromUnix(Convert.ToDouble(profile_time)).ToLongTimeString();
}
string lastUseNetTime = row["last_used_networktime"].ToString();
if (!string.IsNullOrEmpty(lastUseNetTime))
{
CSTimeZone time = new CSTimeZone();
double sec = Convert.ToDouble(lastUseNetTime) * 60;
lastUseNetTime = time.FromUnix(Convert.ToDouble(sec)).ToShortDateString() + " " +
time.FromUnix(Convert.ToDouble(sec)).ToLongTimeString();
}
string lastOnlineTime = row["lastonline_timestamp"].ToString();
if (!string.IsNullOrEmpty(lastOnlineTime))
{
CSTimeZone time = new CSTimeZone();
lastOnlineTime = time.FromUnix(Convert.ToDouble(lastOnlineTime)).ToShortDateString() + " " +
time.FromUnix(Convert.ToDouble(lastOnlineTime)).ToLongTimeString();
}
lst.Add(new CONTACT_INFO()
{
gender=Convert.ToInt32(row["gender"].ToString()),
timezone=row["timezone"].ToString(),
fullName = row["fullname"].ToString(),
profile_timestamp = profile_time,
last_used_networktime = lastUseNetTime,
lastonline_timestamp = lastOnlineTime,
birthday = string.IsNullOrEmpty(sDate) ? "" : datetime
});
}
}
return lst;
}
The function FromUnix is written as
public DateTime FromUnix(double seconds)
{
DateTime datetime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).ToLocalTime();
return datetime.AddSeconds(seconds);
}
I am pretty sure this is a parsing problem
The following line would throw exceptions if the value of sDate is not in the defined format of yyyyMMdd
datetime = DateTime.ParseExact(sDate, format, provider).ToShortDateString();
I would first use TryParseExact instead of a simple Parse since you do not seem to be using try/catch clauses. It might be a good idea to use the debugger to see exactly where your program is failing.
Other example of potential failures in your code are
double sec = Convert.ToDouble(lastUseNetTime) * 60;
Use double.tryParse
Convert.ToInt32(row["gender"].ToString()
If gender turns out not to be a number another exception will be thrown
etc...

How do I convert DateTime .NET datatype to W3C XML DateTime data type string and back?

I have a System.DateTime object and I need to convert it into a string storing that datetime in W3C XML DateTime format (yyyy-mm-ddThh:mm:ssZ) and then be able to convert the resulting string back into System.DateTime.
Is there something ready for that in .NET or do I have to implement it myself?
I thought W3C dateTime had a lot more significant digits for the time.
Here's what I use:
// DateTime to W3C dateTime string
string formatString= "yyyy-MM-ddTHH:mm:ss.fffffffzzz";
dateTimeField.ToString(formatString) ;
// W3C dateTime string to DateTime
System.Globalization.CultureInfo cInfo= new System.Globalization.CultureInfo("en-US", true);
dateTimeField= System.DateTime.ParseExact(stringValue, formatString, cInfo);
If you want a date in the W3C XML format, then use .Net's W3C XML formatting API (been there since before v1.0):
var w3cStringFormat = XmlConvert.ToString(DateTime.Now);
results in:
2014-09-12T16:03:22.6833035+01:00
Then to get it back again:
var dateTime = XmlConvert.ToDateTime(w3cStringFormat);
This will convert to the string you need and parse back the string to the DateTime:
var now = DateTime.Now;
Console.WriteLine(now.ToUniversalTime().ToString());
var nowString = now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");
Console.WriteLine(nowString);
var nowAgain = DateTime.ParseExact(nowString, "yyyy-MM-ddTHH:mm:ssZ", null);
Console.WriteLine(nowAgain.ToUniversalTime().ToString());
Console.ReadLine();
I would think JSON.net can handle it.
Use IsoDateTimeConverter.
From documentation:
public class LogEntry
{
public string Details { get; set; }
public DateTime LogDate { get; set; }
}
[Test]
public void WriteJsonDates()
{
LogEntry entry = new LogEntry
{
LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
Details = "Application started."
};
string defaultJson = JsonConvert.SerializeObject(entry);
// {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
// {"Details":"Application started.","LogDate":new Date(1234656000000)}
string isoJson = JsonConvert.SerializeObject(entry, new IsoDateTimeConverter());
// {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}
}
Xml Serialization is there for you. Below is the code how to:-
DateTime someDateTime = DateTime.Now.AddDays(5);
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(DateTime));
System.IO.MemoryStream ms = new System.IO.MemoryStream();
// converting to w3c xml
ser.Serialize(ms, someDateTime);
//**Edited**
ms.Position = 0;
//**Edited**
System.IO.StreamReader sr = new System.IO.StreamReader(ms);
string w3cxml = sr.ReadToEnd();
sr.Close();
ms.Close();
// doing reverse
System.IO.StringReader reader = new System.IO.StringReader(w3cxml);
DateTime thatDateTime = (DateTime)ser.Deserialize(reader);
reader.Close();

Categories