I am using the Vimeo API and I want to convert the string <upload_date> to a short date format, {0:d} or {0:dd/mm/yyyy}.
This is my code but it doesn't seem to be working for me.
select new VimeoVideo
{
Date = String.Format("{0:d}",(item.Element("upload_date").Value)),
};
return Vids.ToList();
}
public class VimeoVideo
{
public string Date { get; set; }
}
As Oleg suggested you can try to parse your value to DateTime and then format it (use try catch if needed). That should work (not 100% sure since I don't know what item's type is).
var myDate = DateTime.Parse(item.Element("upload_date").Value);
Date = String.Format("{0:d}", myDate);
http://msdn.microsoft.com/it-it/library/1k1skd40(v=VS.80).aspx
Just verify the type of the Value property.. The above string formatter works for System.DateTime structure.. I assume in your case its string type object. According to the given sample date time string i have written this code.. Try out this.
CultureInfo provider = CultureInfo.InvariantCulture;
var format = "yyyy-MM-dd HH:mm:ss";
var dt = DateTime.ParseExact(item.Element("upload_date").Value, format, provider);
Date = string.Format("{0:d}", dt);
Hope it works..
Related
I want to convert a string of date format to a string with another format.
The string DateOfBirth could be in different formats such as:
01/15/2017
01-15-2017
1.15.2017
1.5.2017
I want to convert it to another pattern that I get it as parameter.
public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
}
Let's assume that date = "01/15/2017" and convertToDateFormat = "YYYY/MM/DD". How could I change it to the new format?
The problem for me was to do it generic so that it will accept any parametrs.
I thought that I can convert date to DateTime and then to use ToString with the format but can you offer any better idea?
Parse to DateTime and then back to String:
public string ConvertStringDateFormat(string date, string convertToDateFormat) {
return DateTime
.ParseExact(date,
new string[] { "M/d/yyyy", "M-d-yyyy", "M.d.yyyy" },
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeLocal)
.ToString(convertToDateFormat); // convertToDateFormat = #"yyyy\/MM\/dd" for YYYY/MM/DD
}
i think this will work :
(Convert.ToDateTime(date)).ToString(convertToDateFormat)
try this
public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
return Convert.ToString(Convert.ToDateTime(date),convertToDateFormat);
}
I have a set of array.
//this is not hard corded, some times array will have multiple no.of strings in date format.
["vishnu","2016-08-31T18:30:00.000Z","1992","banglore"]
I have an array of strings, among these strings there is one string which is in date format.
I need to do a foreach and need to check which string is in the date format.
If we got the date string "2016-08-30T18:30:00.000Z" I need to convert it to basic date format but in correct timezone, here the date is 2016-08-31 but what I need as out put is
["vishnu","31/8/2016","1992","banglore"]
not
//check the difference in date!
["vishnu","30/8/2016","1992","banglore"]
the aim is from the array, if string is in date string format, convert it.
public static void Main(string[] args)
{
string inputString = "2016-08-31T18:30:00.000Z";
DateTime enteredDate = DateTime.Parse(inputString);
Console.WriteLine(enteredDate);
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime dtx = enteredDate.ToLocalTime();
String.Format("{0:d/MM/yyyy}", dDate);
Console.WriteLine(dtx);
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
// DateTime dt = convertedDate.ToLocalTime();
}
If you need to correct the DateTime for the time zone, you can use TimezoneInfo.ConvertTime():
string inputString = "2016-08-31T18:30:00.000Z";
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime correctedDateTime = TimeZoneInfo.ConvertTime(dDate, TimeZoneInfo.Local);
// write this here back into the array using your format
Console.WriteLine(correctedDateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
For further reference check out this post. This answer is inspired by it to use TimeZoneInfo.
DateTime dDate;
do this operation iside foreach
if (DateTime.TryParse(answerString, out dDate))
{
DateTime enteredDate = DateTime.Parse(answerString);
var Date = enteredDate.ToString("dd/MM/yyyy");
answerString = Date;
Console.WriteLine(answerString);
}
else{
//operation
}
thanks to mong zhu
Try using DateTimeOffset rather than DateTime as it is built to handle time zones.
Here's the code:
string inputString = "2016-08-31T18:30:00.000Z";
DateTimeOffset enteredDate = DateTimeOffset.Parse(inputString);
Console.WriteLine(enteredDate);
DateTimeOffset dtx = enteredDate.ToLocalTime();
Console.WriteLine(dtx);
This produces the following for me in GMT+09:30:
2016/08/31 18:30:00 +00:00
2016/09/01 04:00:00 +09:30
To get it in Indian time try this:
DateTimeOffset dtx = enteredDate.ToOffset(TimeSpan.FromHours(5.5));
Console.WriteLine(dtx);
I get 2016/09/01 00:00:00 +05:30 now.
I have this CSV
"06/04/2016 17:24:14,1443.92,0.31"
Which I try to convert into the following object
public class FooModel
{
public DateTime Date { get; set; }
public DateTime Time { get; set; }
public string Index { get; set; }
public string Change { get; set; }
}
with the following code
string[] values = line.Split(',');
FooModel m = new FooModel
{
Date = DateTime.ParseExact(values[0], "dd/MM/yyyy", CultureInfo.InvariantCulture),
Time = DateTime.ParseExact(values[0], "H:mm:ss", CultureInfo.InvariantCulture),
CultureInfo.InvariantCulture),
Index = values[1],
Change = values[2],
};
and failing on the exception
"String was not recognized as a valid DateTime."
How can I cast to DateTime Object
EDIT
I saw couple of answers that almost worked however it was my bad to mention that the date is formatted as Day-Month-Year. this means that it is failing when the csv is set to "22/12/2014 16:24:04,1476.83,-0.74"
I would guess the issue you're having is with the ParseExact part of this.
Why are you converting both the date and the time separately? It seems easier to do this:
DateTime Date = DateTime.Parse(values[0]);
string time = Date.ToLongTimeString();
string date = Date.ToLongDateString();
This way it's saved in the same variable and you can use the pieces as you need.
From the documentation:
The format of the string representation must match the specified format exactly.
The input string is:
"06/04/2016 17:24:14,1443.92,0.31"
The format string is:
"dd/MM/yyyy"
Those aren't really exact. Just use Parse instead:
Date = DateTime.Parse(values[0]);
This gives you the complete DateTime value, so you don't even need the Time property on the model. No need to store the same information twice, after all.
Additionally, you might use TryParse to be a little safer with the input:
DateTime temp;
if (!DateTime.TryParse(values[0], out temp))
{
// parsing error. notify the user?
}
Date = temp;
string[] s = "06/04/2016 17:24:14,1443.92,0.31".Split(',');
DateTime date = DateTime.Parse(s[0]);
This worked for me.
When you split the string values[0] = 06/04/2016 17:24:14 and you are parsing the Date and the Time component separately. Instead you need to parse them together with
DateTime date = DateTime.ParseExact(values[0], "dd/MM/yyyy H:mm:ss",
CultureInfo.InvariantCulture);
and access the date by
date.Date
and access the time by
date.Time
in my code i can get 2 types of string that represents dateTime:
1."2013-09-05T15:55"
2."09-05T19:10"
How do i convert it to a valid DateTime?
i tried the following code but it throws an exception for the second format:
String departureDateStr = "09-05T19:10";
DateTime dt = Convert.ToDateTime(departureDateStr);
how do i convert the second type of string to a valid DateTime ?
do i need some kind of string manipulation?
thx,
Amir
DateTime.TryParseExact has an overload that allows you to pass multiple formats as an array. Each date string is then compared with the various formats within the array so you don't need to know ahead of time which format to look for.
string d1 = "2013-09-05T15:55";
string d2 = "09-05T19:10";
string[] formats = new string[] { "yyyy-MM-ddTHH:mm", "MM-ddTHH:mm" };
List<string> dates = new List<string>() { d1, d2 };
foreach (string date in dates)
{
DateTime dt;
if (DateTime.TryParseExact(date, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
{
//dt successfully parsed
}
}
TryParseExact also returns false instead of throwing an exception if none of the formats in the array matched the input.
Use DateTime.ParseExact method with custom datetime format string:
string departureDateStr = "09-05T19:10";
string departureDateStr2 = "2013-09-05T19:10";
var dt = DateTime.ParseExact(departureDateStr, "MM-ddTHH:mm", System.Globalization.CultureInfo.InvariantCulture);
var dt2 = DateTime.ParseExact(departureDateStr2, "yyyy-MM-ddTHH:mm", System.Globalization.CultureInfo.InvariantCulture);
or universal call for both formats:
var dt = DateTime.ParseExact(departureDateStr, new[] { "MM-ddTHH:mm", "yyyy-MM-ddTHH:mm" }, System.Globalization.CultureInfo.InvariantCulture);
You can use DatetIme.ParseExact() method for this. It converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.
String departureDateStr = "09-05T19:10";
IFormatProvider provider = System.Globalization.CultureInfo.InvariantCulture;
string format = "MM-ddTHH:mm";
DateTime parsedDate = DateTime.ParseExact(departureDateStr, format, provider);
If you need this conversion a lot of times, then you can even make it an extension method as below:
public static class StringExtensions
{
public static DateTime ToDate(this string str)
{
IFormatProvider provider = System.Globalization.CultureInfo.InvariantCulture;
string format = "MM-ddTHH:mm";
return DateTime.ParseExact(str, format, provider);
}
}
I have a string that is formatted as YYYYMMDD - how can i make a copy in the format YYYY-MM-DD?
// this is your original string
string _str = "20130101";
// you need to convert it to valid DateTime datatype
// so you can freely format the string to what you want
DateTime _date = DateTime.ParseExact(_str, "yyyyMMdd", CultureInfo.InvariantCulture);
// converting to your desired format, which is now a string
string _dateStr = _date.ToString("yyyy-MM-dd");
DateTime.ParseExact()
You'll have to parse the DateTime, then reformat it:
var input = ...
var inFormat = "yyyyMMdd";
var outFormat = "yyyy-MM-dd";
var date = DateTime.ParseExact(inFormat, input, CultureInfo.InvariantCulture);
var output = date.ToString(outFormat);
the safe approach is to convert it to DateTime Object , for example in .Net using below function :
DateTime.TryParseExact()
and then using the DateTime Object you can format it again. like below example :
dateTimeObject.ToString(YourFormatInString);
check MSDN for more details : http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx