Date format issue in C# - c#

I get a date in C# from javascript in this format:
"Tue Jan 15 00:00:00 UTC+0530 2008".
How can I convert this to "dd/MMM/yyyy" format?

var jsdate = "Tue Jan 15 00:00:00 UTC+0530 2008";
var format = "ddd MMM d HH:mm:ss UTCzzzzz yyyy";
var date = DateTime.ParseExact(jsdate, format, CultureInfo.InvariantCulture);
Console.WriteLine(date.ToString("dd/MMM/yyyy"));

Try this:
var test = "Tue Jan 15 00:00:00 UTC+0530 2008";
const string format = "ddd MMM d HH:mm:ss zzz yyyy";
var var = DateTime.ParseExact(test.Replace("UTC", ""), format, CultureInfo.InvariantCulture);
Console.WriteLine(var);

Related

Trim a string to get date in middle? [duplicate]

This question already has an answer here:
Extract date in a string C#?
(1 answer)
Closed 6 years ago.
I need the following string trimmed
Sat, 02/04/1708:00 PM
so that the result is 02/04/17
How can I accomplish this?
you can use Split() and Substring()
var str = #"Sat, 02/04/1708:00 PM";
var res = str.Split(' ')[1].Substring(0, 8);
Regex rg = new Regex(#"[01]?\d[/-][0123]?\d[/-]\d{2}");
Match m = rg.Match("Sat, 02/04/1708:00 PM");
Console.Write(m.ToString());
WORKING FIDDLE
you can use substring
string str="Sat, 02/04/1708:00 PM";
string newStr=str.Substring(5,8);
You can also do this:
string strInput = #"Sat, 02/04/1708:00 PM";
var dateResult = strInput.Split(' ', ',')[2];
This might do the trick for you.
string smdt = "Sun, 02/04/1708:00 PM";
string format = "ddd, dd/MM/yyhh:mm tt";
DateTime dt = DateTime.ParseExact(smdt, format, CultureInfo.InvariantCulture, DateTimeStyles.None);
string extractedDate = dt.ToString("dd/MM/yy");
The problem with the Question was the Date 02/04/17 is not a Saturday instead it will be Sunday and thus it will not be able to convert to a DateTime. When I change Sat to Sun. The extractedDate is the result which you are looking for.
One liner answer could be
string smdt = "Sun, 02/04/1708:00 PM";
string extractedDate = DateTime.ParseExact(
smdt,
"ddd, dd/MM/yyhh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None
).ToString("dd/MM/yy");
String str = #"Sat, 02/04/1708:00 PM";
String expected = str.split(' ')[1].Substring(0,8);

Convert string to datetime in any format

Aim :
want to convert date time in any format to de-DE culture
Sample Datetime :
3/30/2016 2:38:20 PM
4/4/2016 11:08:10 AM
What I tried
protected void Page_Load(object sender, EventArgs e)
{
string dt1Valid = CheckDateFormat("3/30/2016 2:38:20 PM");
}
public string CheckDateFormat(string checkDate)
{
string formats1 = getFormat(checkDate);
DateTime parsedDateTime;
DateTimeFormatInfo ukDtfi = new CultureInfo("de-DE", false).DateTimeFormat;
if (!DateTime.TryParseExact(checkDate, formats1, new CultureInfo("de-DE"),
DateTimeStyles.None, out parsedDateTime))
{
return Convert.ToDateTime(parsedDateTime.ToString()).ToString(ukDtfi.ShortDatePattern + " " + ukDtfi.LongTimePattern);
}
else
return "";
}
public string getFormat(string checkDate)
{
string[] formats = {"M/d/yyyy", "MM/dd/yyyy",
"d/M/yyyy", "dd/MM/yyyy",
"yyyy/M/d", "yyyy/MM/dd",
"M-d-yyyy", "MM-dd-yyyy",
"d-M-yyyy", "dd-MM-yyyy",
"yyyy-M-d", "yyyy-MM-dd",
"M.d.yyyy", "MM.dd.yyyy",
"d.M.yyyy", "dd.MM.yyyy",
"yyyy.M.d", "yyyy.MM.dd",
"M,d,yyyy", "MM,dd,yyyy",
"d,M,yyyy", "dd,MM,yyyy",
"yyyy,M,d", "yyyy,MM,dd",
"M d yyyy", "MM dd yyyy",
"d M yyyy", "dd MM yyyy",
"yyyy M d", "yyyy MM dd",
"M/d/yyyy hh:mm:ss tt", "MM/dd/yyyy hh:mm:ss tt",
"d/M/yyyy hh:mm:ss tt", "dd/MM/yyyy hh:mm:ss tt",
"yyyy/M/d hh:mm:ss tt", "yyyy/MM/dd hh:mm:ss tt",
"M-d-yyyy hh:mm:ss tt", "MM-dd-yyyy hh:mm:ss tt",
"d-M-yyyy hh:mm:ss tt", "dd-MM-yyyy hh:mm:ss tt",
"yyyy-M-d hh:mm:ss tt", "yyyy-MM-dd hh:mm:ss tt",
"M.d.yyyy hh:mm:ss tt", "MM.dd.yyyy hh:mm:ss tt",
"d.M.yyyy hh:mm:ss tt", "dd.MM.yyyy hh:mm:ss tt",
"yyyy.M.d hh:mm:ss tt", "yyyy.MM.dd hh:mm:ss tt",
"M,d,yyyy hh:mm:ss tt", "MM,dd,yyyy hh:mm:ss tt",
"d,M,yyyy hh:mm:ss tt", "dd,MM,yyyy hh:mm:ss tt",
"yyyy,M,d hh:mm:ss tt", "yyyy,MM,dd hh:mm:ss tt",
"M d yyyy hh:mm:ss tt", "MM dd yyyy hh:mm:ss tt",
"d M yyyy hh:mm:ss tt", "dd MM yyyy hh:mm:ss tt",
"yyyy M d hh:mm:ss tt", "yyyy MM dd hh:mm:ss tt"
};
DateTime dateValue;
foreach (string dateStringFormat in formats)
{
if (DateTime.TryParseExact(checkDate, dateStringFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateValue))
//Console.WriteLine("Converted '{0}' to {1}.", dateStringFormat, dateValue.ToString("yyyy-MM-dd"));
return dateStringFormat;
}
return null;
}
Result i expect
30.03.2016 14:38:20
04.04.2016 11:08:10
Result i get
01.01.0001 00:00:00
01.01.0001 00:00:00
That's simple to answer: It's not possible, so stop trying.
Proof: Any format includes M.d.yyyy as well as d.M.yyyy. In that case, 1.2.2016 can represent either
the first of February or
the second of January.
Conclusion: A translation from any format is not possible, since it's not possible to parse ambiguous dates without additional information.
Note: This has nothing to do with C# or your technology of choice. Your requirements are broken. Fix them.

Convert.ToDateTime in Java

Here's my code in c#.
DateTime gmtTime = Convert.ToDateTime(string.Format("{0} {1}", day[1], day[2])).Add(Convert.ToDateTime(time).TimeOfDay);
What I've tried in Java.
String month = "Jul";
String day = "22";
String gmtTime = String.format("%s %s", month, day);
DateFormat df = new SimpleDateFormat("MMM dd");
Date gmtDate = df.parse (gmtTime);
The result I'm getting into Java is July 22, 1970. How can I get the current year just like in C# when I convert a String to DateTime the year is the current year. Is possible to have a code just like what I've tried in my c# code to transfer it to Java?
Hoping to get a good result. Thanks
Calendar cal=Calendar.getInstance();
int year=cal.get(Calendar.YEAR);
System.out.println(year);
Will give the current year
Change these lines:
String gmtTime = String.format("%s %s", month, day);
DateFormat df = new SimpleDateFormat("MMM dd");
To this:
String gmtTime = String.format("%s %s %s", month, day, Calendar.getInstance().get(Calendar.YEAR));
DateFormat df = new SimpleDateFormat("MMM dd yyyy");
Try adding year to your Java SimpledateFormat, see the formats used here http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#year
DateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");
final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy hh:mm:ss a z");
// Set time zone
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current Time: " + sdf.format(currentTime));
Here simply formatting current date-
final DateFormat reportDateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);
Date date = new Date();
String dateString = reportDateFormat.format(date);
System.out.println(dateString);

DateTime ParseExact exception

var str = "00:00:00 02/01/1990";
var dt = DateTime.ParseExact(str, "hh:mm:ss dd/MM/yyyy", null);
The above code is throwing an exception "String was not recognized as a valid DateTime."
I thought using ParseExact and specifying the exact format this would be okay. What is wrong with the above?
EDIT:
Solved using invariant culture. Thanks for comments.
var dt = DateTime.ParseExact(str, "HH:mm:ss dd/MM/yyyy", CultureInfo.InvariantCulture);
The "hh" format specifier is for 12-hour AM/PM time, which doesn't support a "00". Try defining it in 24-hour time: HH:mm:ss dd/MM/yyyy
Yes usually in DateTime format the Date comes first before Time. Try this out:
var str = "02/01/1990 00:00:00";
var dt = DateTime.ParseExact(str, "hh:mm:ss dd/MM/yyyy", null);
EDITED: OK so you do one trick to get it done:
var str = "00:00:00 02/01/1990";
var split = str.Split(new char[] { ' ' });
if (split.Length == 2)
str = String.Format("{0} {1}", split[1], split[0]);
var dt = DateTime.ParseExact(str, "hh:mm:ss dd/MM/yyyy", null);

convert datetime to date format dd/mm/yyyy

I have a DateTime object 2/19/2011 12:00:00 AM. I want to convert this object to a string 19/2/2011.
Please help me to convert DateTime to string format.
DateTime dt = DateTime.ParseExact(yourObject.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
First of all, you don't convert a DateTime object to some format, you display it in some format.
Given an instance of a DateTime object, you can get a formatted string in that way like this:
DateTime date = new DateTime(2011, 2, 19);
string formatted = date.ToString("dd/M/yyyy");
As everyone else said, but remember CultureInfo.InvariantCulture!
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture)
OR escape the '/'.
You have to pass the CultureInfo to get the result with slash(/)
DateTime.Now.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
DateTime.ToString("dd/MM/yyyy") may give the date in dd-MM-yyyy format. This depends on your short date format. If short date format is not as per format, we have to replace character '-' with '/' as below:
date = DateTime.Now.ToString("dd/MM/yyyy").Replace('-','/');
It's simple--tostring() accepts a parameter with this format...
DateTime.ToString("dd/MM/yyyy");
Here is a method, that takes datetime(format:01-01-2012 12:00:00) and returns string(format: 01-01-2012)
public static string GetDateFromDateTime(DateTime datevalue){
return datevalue.ToShortDateString();
}
You can use the ToString() method, if you want a string representation of your date, with the correct formatting.
Like:
DateTime date = new DateTime(2011, 02, 19);
string strDate = date.ToString("dd/MM/yyyy");
In C# 10 you can use DateOnly.
DateOnly date = new(2011, 02, 19);
string output = date.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
If you want the string use -
DateTime.ToString("dd/MM/yyyy")
On my login form I am showing the current time on a label.
public FrmLogin()
{
InitializeComponent();
lblTime.Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");
}
private void tmrTime_Tick(object sender, EventArgs e)
{
lblHora.Text = DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt");
}
string currentdatetime = DateTime.Now.ToString("dd'/'MM'/'yyyy");
DateTime.Parse(YOUR_DATE_OBJECT).ToShortDateString();
ToShortDateString() method will help you convert DateTime To Just Date String,format dd/mm/yyyy.
This works for me:
string dateTimeString = "21‎-‎10‎-‎2014‎ ‎15‎:‎40‎:‎30";
dateTimeString = Regex.Replace(dateTimeString, #"[^\u0000-\u007F]", string.Empty);
string inputFormat = "dd-MM-yyyy HH:mm:ss";
string outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
string output = dateTime.ToString(outputFormat);
Console.WriteLine(output);
this is you need and all people
string date = textBox1.Text;
DateTime date2 = Convert.ToDateTime(date);
var date3 = date2.Date;
var D = date3.Day;
var M = date3.Month;
var y = date3.Year;
string monthStr = M.ToString("00");
string date4 = D.ToString() + "/" + monthStr.ToString() + "/" + y.ToString();
textBox1.Text = date4;

Categories