How can I convert the english date 10/29/2010 or any language date to user culture date format
I am using the following code
CultureInfo cultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;
cultureInfo.DateTimeFormat.
string lng = cultureInfo.TwoLetterISOLanguageName;
DateTime dateTime = DateTime.Parse("10/29/2010", cultureInfo);
but it throws error when I try to parse it.
Any Idea how can I resolve this issue
Thanx
Use ParseExact with English (or invariant) culture to convert the String into a datetime, then you can use ToString to output in in the user's date format.
// this is in "d" (= short date) format of the invariant culture
var englishDateString = "10/29/2010";
// convert it to a datetime
var date = DateTime.ParseExact(englishDateString, "d", CultureInfo.InvariantCulture);
// now you can output the date in the user's culture
var localizedDateString = date.ToString("d");
If you want to be explicit, you can add CultureInfo.CurrentCulture as a second parameter to ToString, but it's not required, since this is the default if no culture is specified.
Here's an example of parsing a US date:
DateTime.Parse("10/29/2010", new CultureInfo("en-US"));
i had the same pain when facing date conversion and i used a function (code below), you can modify it as you wish. try it or get ideas from it and let me know if it was useful
Imports Microsoft.VisualBasic Imports System.Globalization Public Class DatumKonvert1
Public Shared Function DK1(ByVal myDMstring As String) As Date
Dim source As String = myDMstring
Dim d As DateTime = DateTime.ParseExact(source, "d'/'M'/'yyyy", CultureInfo.InvariantCulture)
Dim resultMydate As String = d.ToString("M'/'d'/'yyyy")
Dim mdx = DateTime.ParseExact(resultMydate, "M'/'d'/'yyyy", CultureInfo.InvariantCulture)
Return mdx End Function End Class
Use this:
public static string ChangeDateToUserFormat(string dateValue, string dateCulture)
{
CultureInfo dateCultureInfo = CultureInfo.GetCultureInfoByIetfLanguageTag(dateCulture);
DateTime date = DateTime.Parse(dateValue, dateCultureInfo);
return date.ToString(CultureInfo.CurrentCulture);
}
For example:
string date = ChangeDateToUserFormat("10\29\2010", "en-US");
Use DateTime.ParseExact("10/29/2010", "MM/dd/yyyy", CultureInfo.InvariantCulture); instead of DateTime.Parse
Once you have a DateTime, it is no longer bound to a specific culture, but can be output however you want it. Usually, this is with one of the DateTime .ToString methods, or shortcuts like .ToShortDateString(), which uses the current thread's culture.
Edit: Note, it helps if I put the month and day ones in the correct spots. Whoops.
Related
I've been working with the following Lynda.com tutorial on learning MVC 4 and Razor. I'm stuck on trying to have the time that's displayed only shows the hours, minutes, then AM/PM. As of now, the screen still includes the seconds (as seen below):
I tried formatting my dates like this post about DateTime, which didn't work. Now I have the following code within my function in the controller section entitled "AuctionsController.vb", similar to this post:
Function Auction() As ActionResult
Dim mainauction = New MVCAuction3.Models.Auctions
Dim ts As New TimeSpan(10, 0, 0)
mainauction.Title = "Example Auction"
mainauction.Description = "This is an example Auction"
mainauction.StartTime = DateTime.Now + ts
mainauction.EndTime = DateTime.Now.AddDays(7) + ts
mainauction.StartPrice = 1.0
mainauction.CurrentPrice = Nothing
ViewData("Auction") = mainauction
Return View()
End Function
This is how Razor is displaying the content from the view "Auction.vbhtml":
<p>Start Time: #auction.StartTime.ToString() </p>
<p>End Time: #auction.EndTime.ToString()</p>
<p>Starting Price: #FormatCurrency(auction.StartPrice.ToString())</p>
Edit(s):
This is how I declared my time variables in my modal file:
Private Property x_StartTime As DateTime
Private Property x_EndTime As DateTime
Public Property StartTime() As DateTime
Get
Return x_StartTime
End Get
Set(value As DateTime)
x_StartTime = value
End Set
End Property
Public Property EndTime() As DateTime
Get
Return x_EndTime
End Get
Set(value As DateTime)
x_EndTime = value
End Set
End Property
I've also tried to have it from within the "Auction.vhtml" view the following, which unfortunately gave me the server error indicating the "Input string was not in a correct format.":
<p>Start Time: #auction.StartTime.ToString("g") </p>
<p>End Time: #auction.EndTime.ToString("g")</p>
<p>Starting Price: #FormatCurrency(auction.StartPrice.ToString())</p>
What am I doing wrong in either the Razor or MVC code that is not formatting the time? Any help is greatly appreciated!
You should take a look at Custom Date and Time Format Strings on MSDN. Basically, you can pass a format string to the ToString method of your DateTime objects.
Here's a sample that omits the seconds:
auction.StartTime.ToString("M/d/yyyy hh:mm tt")
I would highly suggest looking into the DisplayFormat (MSDN) attribute. You would append it to your models StartTime property like so
[DisplayFormat(ApplyFormatInEditMode=true, DataFormatString = "{0:M/d/yyyy hh:mm tt}")]
public DateTime StartTime {get;set;}
and then you would output the information in your view by the DisplayFor function:
#Html.DisplayFor(x=> x.StartTime)
objTour.tourStartDate =
Convert.ToDateTime(
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", null)
.ToString("MM/dd/yyyy"));
where txtTourStartDate.Text="16/08/2012".
I have searched and read all posts related to this.
In a custom date format string, / denotes the culture-specific date separator, not the literal character /. Thus, the result of your code depends on the user's (or the server's) localization settings.
To make your code independent of culture-specific settings, you have two options:
Explicitly specify a culture that uses a slash as the date separator, e.g.
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy",
CultureInfo.InvariantCulture)
or escape the character, e.g.
DateTime.ParseExact(txtTourStartDate.Text, #"dd\/MM\/yyyy", null)
(note the # and the \).
Both should yield the desired result.
This will be enough:
objTour.tourStartDate = DateTime.ParseExact(txtTourStartDate.Text,
"dd/MM/yyyy",
CultureInfo.InvariantCulture);
Your original code works, although you are doing lot of unnecessary conversions. (DateTime -> ToString -> ToDateTime), the real issue is InvariantCulture. Since you are passing null for CultureInfo try CultureInfo.InvariantCulture.
Your original code:
objTour.tourStartDate =
Convert.ToDateTime(
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
.ToString("MM/dd/yyyy"));
A better one could be:
objTour.tourStartDate =
DateTime.ParseExact(txtTourStartDate.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture)
I'm parsing an XML file from an external source, and I have 2 attributes which contain the date and time respectively. I'm looking for the best way to get these into a format I can parse as a date so I can do things with it, but at the moment I'm just getting errors or no results with the methods I've tried.
The date is in the format "20111215" - which is yyyymmdd as it's UK based.
The time is formatted as "1417+0000" which I presume is the time plus offset from GMT?
Basically I need to get these into UK time. I've tried using DateTime.Parse on the separate parts but both give an error as not valid format. Tried String.Format on the date part but that didn't change it at all. I presume I need to combine the 2 before parsing but I'm not sure if I need to do anything else with it to make it acceptable.
Any help appreciated.
Use a DateTimeOffset to incorporate the timezone into the DateTime.
string date = "20111215";
string time = "1417+0500";
string dateAndTime = date + time;
string format = "yyyyMMddHHmmzzz";
CultureInfo provider = CultureInfo.InvariantCulture;
DateTimeOffset t = DateTimeOffset.ParseExact(dateAndTime, format, provider);
If you concatenate the fields together, you can then use DateTime.TryParseExact in order to parse them into a DateTime.
string input = string.Format("{0} {1}", dateString, timeString);
DateTime parsed;
if(DateTime.TryParseExact(input,
"yyyyMMdd HHmmK",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsed))
{
// parsed OK, use the parsed variable
}
string date = "20111215";
string time = "1417+0000";
string dateString = date + time;;
string format = "yyyyMMddHHmmK";
// or something similar, I'm not sure about the timezone
DateTime result = DateTime.ParseExact(dateString,
format,
CultureInfo.InvariantCulture);
I think this should work (i didn't test it):
string dateString = "20111215";
string timeString = "1417+0000";
int year = int.Parse(dateString.Substring(0,4));
int month = int.Parse(dateString.Substring(4,2));
int day = int.Parse(dateString.Substring(6,2));
int hour = int.Parse(dateString.Substring(0,2));
int mins = int.Parse(dateString.Substring(2,2));
DateTime d = new DateTime(year, month, day, hour, mins, 0);
I have to use java.util.Date class as field type in a table.
But I would like to change the display format of the date field with help of joda time (confortable, prefered to use), thats why I want to convert a Date to DateTime.
I know I oversee something, because there is no such a question in stackoverflow :) but I could not find the soulution among the DateTime constructors and so on.
The reverse conversion DateTime.toDate();
exists, but what about the opposite way ?
Thanks for the answers in advance.
Cs
In Vaadin, if you want to change display format in a table without joda, you simply override the method protected String formatPropertyValue(Object rowId, Object colId,
Property property)
Here an example to do it :
Table t = new Table() {
#Override
protected String formatPropertyValue(Object rowId, Object colId,
Property property) {
Object v = property.getValue();
if (v instanceof Date) {
Date dateValue = (Date) v;
return new SimpleDateFormat("yyyy-MMMM-dd").format(dateValue);
}
return super.formatPropertyValue(rowId, colId, property);
}
};
Regards
Éric
Yes, Use Joda-Time
Definitely use Joda-Time or the java.time package in Java 8 (inspired by Joda-Time). The old java.util.Date and java.util.Calendar classes are notoriously troublesome, confusing, and outmoded.
Also, read the Wikipedia pages on UTC and ISO 8601.
Yes, Pass Date To Joda-Time Constructor
➔ Yes indeed, you can pass a java.util.Date object to the constructor of a Joda-Time DateTime object.
The API doc is a bit confusing as this apparently falls into the catch-all version of the constructor taking an java.lang.Object instance. If that Object is in fact a java.util.Date, Joda-Time will extract its millisecond-count-since-epoch and use that number as its own.
Time Zone
A DateTime constructor also assigns a time zone. By default, the JVM’s current default time zone is assigned. I recommend you always pass a desired time zone rather than rely implicitly on the default even if that means calling getDefault.
Example Code
Here is some example code in Joda-Time 2.5 showing how to pass a java.util.Date to a Joda-Time constructor.
java.util.Date date = new java.util.Date();
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeMontreal = new DateTime( date , zone );
DateTime dateTimeUtc = dateTimeMontreal.withZone( DateTimeZone.UTC ); // Adjust to another time zone.
Dump to console.
System.out.println( "date: " + date ); // Misleading output. A j.u.Date is in UTC but its toString method applies JVM’s current default time zone.
System.out.println( "dateTimeMontreal: " + dateTimeMontreal );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run.
date: Sat Oct 18 18:54:55 PDT 2014
dateTimeMontreal: 2014-10-18T21:54:55.740-04:00
dateTimeUtc: 2014-10-19T01:54:55.740Z
As shown in the Question, to go from a DateTime to java.util.Date, call toDate.
java.util.Date date = dateTimeMontreal.toDate();
Given the following string: 2011/09/18 11:59PM EDT, 2011-09-18T23:59:59+00:00
How do I extract the timezone part from this string using PHP?
Create a new DateTime object from the string, and use getTimezone on it to get the timezone:
$time = '2011/09/18 11:59PM EDT';
$dt = new DateTime($time);
print_r($dt->getTimezone()->getName());
See it in action.