Convert DateTime in C# - c#

I'm trying to convert the DateTime in UTC format to a locale of my choice.
For example, 08.09.2016 17:34:33Z should convert to 08.09.2016 11:34:33 if the locale is set to es-CL.
My code:
public static void Main(string[] args)
{
CultureInfo en = new CultureInfo("es-CL");
Thread.CurrentThread.CurrentCulture = en;
// Creates a DateTime for the local time.
string activityTime = "08.09.2016 17:34:33Z";
DateTime dt = DateTime.Parse(activityTime);
// Converts the local DateTime to the UTC time.
DateTime utcdt = dt.ToUniversalTime();
Console.WriteLine("utc time: " + utcdt.ToString());
// Defines a custom string format to display the DateTime value.
// zzzz specifies the full time zone offset.
String format = "dd/MM/yyyy hh:mm:sszzz";
// Converts the local DateTime to a string
String str = dt.ToString(format);
Console.WriteLine(str);
// Converts the UTC DateTime to a string
String utcstr = utcdt.ToString(format);
Console.WriteLine(utcstr);
// Converts the string back to a local DateTime and displays it.
DateTime parsedBack = DateTime.ParseExact(str,format,en.DateTimeFormat);
Console.WriteLine("local time: " + parsedBack);
DateTime parsedBackUTC = DateTime.ParseExact(str,format, en.DateTimeFormat, DateTimeStyles.AdjustToUniversal);
Console.WriteLine(parsedBackUTC);
}
My output:
utc time: 08-09-2016 17:34:33
08-09-2016 07:34:33+02:00
08-09-2016 05:34:33+02:00
local time: 08-09-2016 7:34:33
08-09-2016 5:34:33
What am I doing incorrectly?

Related

How to convert a string of MM-dd-yyyy to (full month)-yyyy

I have a string variable with the value of 07/31/2016 and I need to convert this to show as July 2016. How can I do this in C#?
var input = "07/31/2016";
var date = DateTime.Parse(input);
var output = date.ToString("MMMM-yyyy");
See DateTime.Parse.
See also date and time format strings.
CultureInfo provider = CultureInfo.InvariantCulture;
var input = "07/31/2016";
var date = DateTime.ParseExact(input,"MM/dd/yyyy",provider);
var output = date.ToString("MMMM-yyyy");
This should be work:
string iDate = "07/31/2016";
DateTime oDate = Convert.ToDateTime(iDate);
Console.WriteLine(CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(oDate.Month) + " " + oDate.Year);
Parse to DateTime and call ToString() with the new format.

Convert ShortTime string to DateTime format

DateTime time = DateTime.Now;
string newTime = time.ToShortTime();
How to convert this newTime string into DateTime format
Please try with the below code snippet.
DateTime time = DateTime.Now;
string newTime = time.ToShortTimeString();
DateTime dt = new DateTime();
DateTime.TryParse(newTime,out dt);
Note : It will set current Date.
Finaly I found an answer
const string FMT = "O";
DateTime now1 = DateTime.Now;
string strDate = now1.ToString(FMT);
DateTime now2 = DateTime.ParseExact(strDate, FMT, CultureInfo.InvariantCulture);

C# String to date with CultureInfo

I have a date in the following format. It is always in this format.
yyyyMMdd -> 20130912
I need to convert it to a date. But I need to be sure that the date is converted to the correct date format of the PC. Cultureinfo.InvariantCulture. Here is what my code looks like now.
DateTime parsedDateTime;
int year = Int32.Parse(rows[row][4].ToString().Substring(0, 4));
int month = Int32.Parse(rows[row][4].ToString().Substring(4, 2));
int day = Int32.Parse(rows[row][4].ToString().Substring(6, 2));
DateTime value = new System.DateTime(year, month, day);
bool DateTimeParseFail = DateTime.TryParse(value.ToString("yyyy-MM-dd"), CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime);
if (!DateTimeParseFail) {
msg = "Data Feed Convert string to DateTime: Date " + rows[row][4].ToString() + " - " + value.ToString();
ComponentMetaData.FireError(0, ComponentMetaData.Name, msg, string.Empty, 0, out pbCancel);
throw new Exception(msg);
} else {
buffer[colIndex] = parsedDateTime;
}
This just looks like overkill to me and I suspect that I'm over-thinking it. There has to be an easier way of doing this. But everything I have tried hasn't worked like I expected it.
Try this:
string dateText = rows[row][4].ToString();
DateTime date = DateTime.ParseExact(dateText, "yyyyMMdd", CultureInfo.InvariantCulture);
string result = date.ToShortDateString(CultureInfo.InvariantCulture.DateTimeFormat.ShortDatePattern);
Note that I'm assuming your assertion that the date is always in this format is correct. If it's not, you'll find that the code throws an exception.
(The code you've posted suggests that your assertion is not true, because you've got a fallback format and some failure handling there...)
Use the TryParseExact of DateTime....
var dateString = "20130912"; //rows[row][4].ToString()
DateTime parsedDateTime;
var DateTimeParseFail= DateTime.TryParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime);
if (!DateTimeParseFail) {
msg = "Data Feed Convert string to DateTime: Date " + rows[row][4].ToString() + " - " + value.ToString();
ComponentMetaData.FireError(0, ComponentMetaData.Name, msg, string.Empty, 0, out pbCancel);
throw new Exception(msg);
} else {
buffer[colIndex] = parsedDateTime;
}

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);

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