- Home /
Formatting Date and Time
hi
i have a textfield taking a string representing a specific DateTime format. I want the string representing the DateTime to be formatted as YYYY-MM-DD, how can i do this?
thanks
Answer by Tetrad · Jun 18, 2010 at 04:09 PM
Use DateTime.TryParse.
You'll probably run into issues if you try to overwrite the string the user is typing while they do that, but if you have an input field and a separate display field that shows the "parsed" date time (formatted like Duck's answer) that would work.
Answer by duck · Jun 04, 2010 at 11:34 AM
Is your value coming from an actual DateTime object? If so, you can do this:
yourTextField.text = String.Format("{0:yyyy-MM-dd}", yourDateTimeObj);
no my value is com$$anonymous$$g from the text field which is a string
ok in that case your question isn't very clear. You have it in a string already, and you want it formatted in a different way? What format is it to begin with?
@Duck, I suspect he means, that a user could enter some random text into a Textfield, and he wants to clean it up. But who knows?
@Cyclops thats what i mean. the user enters a number format for the date (as string) and i want to ensure that its formatted as YYYY-$$anonymous$$$$anonymous$$-DD.
Answer by FarazKhalid · Jun 02, 2014 at 12:32 PM
string computerDate;
string computerTime;
void computerDateAndTime() // read computer current time and date
{
string currentTime=System.DateTime.Now.ToString();
int z=0;
string add="";
for(int i=0;i<currentTime.Length;i++)
{
char item = currentTime[i];
if(item==' ')
{
switch (z)
{
case 0:
computerDate=add;
break;
case 1:
computerTime=add;
break;
}
z++;
add="";
}
else
{
add+=currentTime[i];
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613050938im_/https://answers.unity.com/themes/thub/images/avi.jpg)