RSS pubDate not getting displayed - asp.net

I have an xml file live below
<?xml version="1.0" encoding="utf-8"?><rss version="2.0">
<channel>
<title>About RSS</title>
<link>http://localhost:27549/TTTT.aspx</link>
<description>The latest news</description>
<image><url>http://localhost:27549/images/ttt_logo.jpg</url></image>
<item>
<title>ABC</title>
<link>http://localhost:27549/Viewttt.aspx?id=217</link>
<description>zzzzzzzzzzzzzzzzzzz...</description>
<pubDate>Tuesday, August 30, 2011, 00:00:00AM</pubDate>
</item>
</channel>
</rss>
Though you can see the pubdate tag, it wont get displayed in the pubDate position. This is my code in getting pubdate which does not work,
DateTime dt = DateTime.ParseExact(pubDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
pubDate = dt.ToString("dddd, MMMM dd, yyyy, HH:mm:sstt");
writer.WriteElementString("pubDate", pubDate);
For exmaple I tried getting todays date like below,
writer.WriteElementString("pubDate", DateTime.Now.ToString("r"));
and the date is getting displayed.
What might be wrong in the 1st set of code ?
String pubDate = "";
using (System.Data.Common.DbCommand dbCommand = DataAccess.Instance().Database.GetStoredProcCommand("usp_GetLatestNews"))
{
using (IDataReader reader = DataAccess.Instance().Database.ExecuteReader(dbCommand))
{
int i = 0;
while (reader.Read())
{
if (i == 0)
{
newsHeader = "New News Summary Available for " + reader["Title"].ToString() + " - " + reader["PubDate"];
newsLink = "ViewTTT.aspx?id=" + reader["Id"].ToString();
newsDesc = reader["FullDescription"].ToString();
pubDate = reader["pubDate"].ToString();
DateTime dt = DateTime.ParseExact(pubDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
pubDate = dt.ToString("r");
}
i++;
}
};
}
AddRSSItem(writer, newsHeader, newsUrl, newsDesc, pubDate);
.............
.............
public XmlTextWriter AddRSSItem(XmlTextWriter writer,
string sItemTitle, string sItemLink,
string sItemDescription, String pubDate)
{
writer.WriteStartElement("item");
writer.WriteElementString("title", sItemTitle);
writer.WriteElementString("link", sItemLink);
writer.WriteElementString("description", sItemDescription);
writer.WriteElementString("pubDate", pubDate);
writer.WriteEndElement();
return writer;
}

My suggestion is that you go with the format that you have stated works:
DateTime dt = DateTime.ParseExact(pubDate, "MM/dd/yyyy", CultureInfo.InvariantCulture);
pubDate = dt.ToString("r");
writer.WriteElementString("pubDate", pubDate);
Observe that I'm using the "r" specifier Tue, 30 Aug 2011 00:00:00 GMT as opposed to "dddd, MMMM dd, yyyy, HH:mm:sstt" Tuesday, August 30, 2011, 00:00:00AM which are different formats.

Related

Parse string to DateTime in Flutter (Dart) [duplicate]

This question already has answers here:
How do I convert a date/time string to a DateTime object in Dart?
(8 answers)
Closed 1 year ago.
I am trying to parse String formatted like "23.1.2020" to DateTime object, but nothing works for me. I tried to use some packages like intl or date_format, but none of these can do the job.
DateTime todayDate = DateTime.parse("12.04.2020");
formatDate(todayDate, [yyyy, '/', mm, '/', dd, ' ', hh, ':', nn, ':', ss, ' ', am])
Do you have any idea, how to parse this?
Ok, I found way how to do that:
import 'package:intl/intl.dart';
DateFormat format = DateFormat("dd.MM.yyyy");
print(format.parse(date));
If you are absolutely sure that your date format will always be "dd.MM.yyyy" you could do this :
DateTime todayDate = DateTime.parse("12.04.2020".split('.').reversed.join());
This trick will format your date to "yyyyMMdd" format, which, according to the docs, is accepted by DateTime.parse().
Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below
var date = Jiffy("12.04.2020", "dd.MM.yyyy").format("dd, Oct yy"); // 12, Apr 20
You can also do the following default formats
var date = Jiffy("12.04.2020", "dd.MM.yyyy").yMMMMd; // April 12, 2020
Hope this helps
Fuction Convert date to string :
String dateTostring(DateTime datevalue)
{
String _stringdate ="";
_stringdate = datevalue.month.toString()+"."+datevalue.day.toString()+"."+datevalue.year.toString() ;
return _stringdate;
}
Then fuction convert string to date:
DateTime dateStringtodate(String stringdate)
{
DateTime _stringdate;
List<String> validadeSplit = stringdate.split('.');
if(validadeSplit.length > 1)
{
int day = int.parse(validadeSplit[1].toString()));
int month = int.parse(validadeSplit[0].toString());
int year = int.parse(validadeSplit[2].toString());
_stringdate = DateTime.utc(year, day, month);
}
return _stringdate;
}

java.lang.IllegalArgumentException: Invalid format: "Thu May 24 2018 14:00:00 GMT+0200"

I´m trying to convert a String date like "Thu May 24 2018 14:00:00 GMT+0200" to Joda DateTime (v.2.9.9) but I obtain Invalid format exception:
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
for (int i=0; i < arrayHorarios.length; i++) {
DateTime dateTime = new DateTime();
dateTime = formatter.withOffsetParsed().parseDateTime(arrayHorarios[i]);
}
What am I doing wrong? My goal is to convert all Strings containing dates to Java Dates and then save them into DB... what´s the easiest way to do it? (with or without Joda).
EDIT:
I changed to the correct pattern. Using Java DateFormat was useless too:
ObjectMapper mapper = new ObjectMapper();
String[] arrayHorarios = mapper.readValue(horariosSave, String[].class);
DateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
//sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
List<Date> hor = new ArrayList<Date>();
Date date = new Date();
try {
for (int i=0; i < arrayHorarios.length; i++) {
// conversión de String a Date de los valores
System.out.println("Horario nº:"+i);
System.out.println("String = "+arrayHorarios[i]);
date = df.parse(arrayHorarios[i]);
System.out.println("Date = " + df.format(date));
hor.add(date);
}
System.out.println("Clases guardadas:"+hor.size());
} catch (Exception e) {
e.printStackTrace();
}
This way I get this exception:
java.text.ParseException: Unparseable date: "Fri May 25 2018 12:00:00 GMT+0200"
at java.text.DateFormat.parse(DateFormat.java:366)
java.time
I wonder if there is a way to do it with Java 8 Util Time.
Of course there is.
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
String horario = "Thu May 24 2018 14:00:00 GMT+0200";
OffsetDateTime dateTime = OffsetDateTime.parse(horario, formatter);
System.out.println(dateTime);
Prints:
2018-05-24T14:00+02:00
Imports used are:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
Joda-Time
Not that you’ll regret upgrading to java.time, your Joda-Time code seems to be working too:
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String horario = "Thu May 24 2018 14:00:00 GMT+0200";
DateTime dateTime = formatter.withOffsetParsed().parseDateTime(horario);
System.out.println(dateTime);
This prints:
2018-05-24T14:00:00.000+02:00
I suspect that your problem may be somewhere else.
PS You may already be aware that the Joda-Time home page says:
Users are now asked to migrate to java.time (JSR-310).
To convert Java Date to Joda DateTime:-
Date date = new Date();
DateTime dateTime = new DateTime(date);
With TimeZone, if required:-
TimeZone timeZone= dateTime.getZone().toTimeZone();
DateTime dateTimeNew = new DateTime(date.getTime(), timeZone);
Date dateTimeZone = dateTime.toDateTimeAtStartOfDay(timeZone).toDate();

Formatting Date in Spreadsheet

I have a column in spreadsheet that is 'date'.
When I retrieve the date with the following code,
for (var i = 1; i < data.length; ++i) {
var row = data[i];
var date= row[0];
Logger.log(date);
I get
Wed Nov 12 2014 00:00:00 GMT+0800 (HKT)
Is there a way to just show the output as
Wed Oct 15 2014
I tried converting to JSON since it is an object, so that I can use substring
startDate = JSON.stringify(startDate);
startDate = startDate.substring(0, 14);
But it doesn't output correctly.
"2014-11-12T16:00:00.000Z"
Use formatDate() from the "Utilities" class:
var formattedDate = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'T'HH:mm:ss'Z'");
https://developers.google.com/apps-script/reference/utilities/utilities#formatDate(Date,String,String)
Did you try using "formatDate" in Utilities class
formatDate(date, timeZone, format)
try doing this:
var dateToFormat = row[0];
var formattedDate = Utilities.formatDate(new Date(dateToFormat), "GMT", "EEE, MMM d, yyyy");
Logger.log(formattedDate);

datetime parsing from excel sheet in asp.net

i want to get a datetime value from excel sheet and take the highest and the lowest date
i read the excel sheet and put it in datatable :
i tried this code :
protected void CheckTheFP(DataTable data)
{
if (data.Rows.Count != 0)
{
DateTime ds = new DateTime();
err.Text = DateTime.TryParseExact(data.Rows[0][2].ToString(), "MM/dd/yy hh:mm tt",
CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out ds) + "" ;
}
}
but i always get false ... don't know why ?
and is there a way to sort this datatable or take the highest and lowest date
this the excel sheet i read from
This format string should work: "M/dd/yy h:mm tt". I've used single M because the month has one digit, the same applies to the hours. I've used CultureInfo.InvariantCulture to prevent that all / will be replaced with your actual date-separator (in case that it's different).
You can use LINQ:
var allDateTimes = data.AsEnumerable()
.Select(row => DateTime.ParseExact(row.Field<string>("Time"), "M/dd/yy h:mm tt", CultureInfo.InvariantCulture));
DateTime min = allDateTimes.Min();
DateTime max = allDateTimes.Max();
If you want to be on the safe side you should use TryParseExact, for example with this code:
IEnumerable<DateTime> allDateTimes = data.AsEnumerable()
.Select(row => {
string time = row.Field<string>("Time").Trim();
DateTime dt;
if (DateTime.TryParseExact(time, "M/dd/yy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
return (DateTime?) dt;
return null; // set a breakpoint here to see which value could not be parsed
})
.Where(dt => dt.HasValue)
.Select(dt => dt.Value);
DateTime min = allDateTimes.Min();
DateTime max = allDateTimes.Max();
Edit: you: "when i try to use it on the date 11/2/14 4:42 PM you see the 11 is not in M datetime format
The month is not the problem. Use single d instead because the days can have a single digit also.
So: "M/d/yy h:mm tt"

How to convert date string to specific date format?

I get date string value(3/13/2013 12:00:00AM) from database and i need to convert like this format (yyyy-mm-dd). Please help me solve this.
string targetdate = "3/13/2013 12:00:00AM";(getting date value from DB)
DateTime lastdate = DateTime.ParseExact(targetdate, "yyyy-mm-dd",
System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
And I tried
Iformatprovider = null.
but i getting same error "String was not recognized as a valid DateTime"
I think the problem is with the date time
"3/13/2013 12:00:00AM"
It should not be 12:00:00AM.
It should be 12:00:00PM.
Example
string targetdate = "3/13/2013 11:59:59AM";
DateTime lastdate = DateTime.ParseExact(targetdate,
"M/d/yyyy HH:mm:sstt",
System.Globalization.CultureInfo.InvariantCulture);
lastdate=lastdate.AddSeconds(1);
You will get
3/13/2013 12:00:00 AM
I would suggest you to cast it in the database end.
If you are using sql server then
Example
The following script uses the CONVERT() function to display different formats. We will use the GETDATE() function to get the current date/time:
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
The result would look something like this:
Nov 04 2011 11:45 PM
11-04-11
11-04-2011
04 Nov 11
04 Nov 2011
04 Nov 2011 11:45:34:243
First you need to convert your date string to DateTime type object using the format "M/d/yyyy HH:mm:sstt" later you can get the formatted string using "yyyy-MM-dd". (You used lower case m for month, it should be upper case M for month.
string targetdate = "3/13/2013 12:00:00AM";
DateTime lastdate = DateTime.ParseExact(targetdate,
"M/d/yyyy hh:mm:sstt",
System.Globalization.CultureInfo.InvariantCulture);
string newFormat = lastdate.ToString("yyyy-MM-dd");
newFormat would contain "2013-03-13"
DateTime conversion is really easy in .Net if you know which datetime format you have and in which format you convert that.
Here is example for this.
String origionalDate = "12/20/2013"; // Format : MM/dd/yyyy
string origionalFormat = "MM/dd/yyyy";
string convertInToFormat="dd/MM/yyyy";
String convertedDate;
DateTime objDT;
if (DateTime.TryParseExact(origionalDate, origionalFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out objDT) == true)
{
convertedDate = objDT.ToString(convertInToFormat);
Response.Write("<b>Origional DateTime Format ( " + origionalFormat + " ) : </b>" + origionalDate);
Response.Write("<br/>");
Response.Write("<b>Converted DateTime Format ( " + convertInToFormat + " ) : </b>" + convertedDate);
}
else
{
Response.Write("<b>Not able to parse datetime.</b>");
}
For more details on this visit this link. Click Here...

Resources