How to Convert a Date String to Different Format

Convert String Date to String date different format

SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("2013-02-21");
System.out.println(format2.format(date));

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

Convert Date String to another Date string with different format

What you are doing is fine.

Probably you can improve it by using DateTime.TryParseExact and on successful parsing, format the DateTime object in other format.

string dateString = "20130916";
DateTime parsedDateTime;
string formattedDate;
if(DateTime.TryParseExact(dateString, "yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out parsedDateTime))
{
formattedDate = parsedDateTime.ToString("MM/dd/yyyy");
}
else
{
Console.WriteLine("Parsing failed");
}

Formatting a String date into a different format in Java

Use this code to format your `2017-05-23T06:25:50'

String strDate = "2017-05-23T06:25:50";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(strDate);
SimpleDateFormat sdfnewformat = new SimpleDateFormat("MMM dd yyyy");
String finalDateString = sdfnewformat.format(convertedDate);
} catch (ParseException e) {
e.printStackTrace();
}

The converted finalDateString set to your textView

swift - Convert a String to a Date and then to a String in a different format

Updated for Swift 3.0

You need two date formatters - one to make sense of your input string and convert to a NSDate, and a different formatter to create the output string

    let myDateString = "2016-01-01 04:31:32.0"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.A"
let myDate = dateFormatter.date(from: myDateString)!

dateFormatter.dateFormat = "MMM dd, YYYY"
let somedateString = dateFormatter.string(from: myDate)

I have updated this answer to change the date formatter from YYYY to yyyy. In most cases, there will be no difference between the two, but YYYY may treat the first few days of the year as being part of the last complete week of the previous year.

The Apple developer guides explain it like this.

A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.

Convert string of date format to string of another date format

try this

public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
return Convert.ToString(Convert.ToDateTime(date),convertToDateFormat);
}

Converting date-string to a different format

Use java.util.DateFormat:

DateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd");
fromFormat.setLenient(false);
DateFormat toFormat = new SimpleDateFormat("dd-MM-yyyy");
toFormat.setLenient(false);
String dateStr = "2011-07-09";
Date date = fromFormat.parse(dateStr);
System.out.println(toFormat.format(date));

Parse String to Date with Different Format in Java

Take a look at SimpleDateFormat. The code goes something like this:

SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");

try {

String reformattedStr = myFormat.format(fromUser.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}

Convert string date to a different format in pandas dataframe

If you convert the column of strings to a time series, you could use the dt.strftime method:

import numpy as np
import pandas as pd
nan = np.nan
df = pd.DataFrame({'TBD': [nan, nan, nan], 'TBD.1': [nan, nan, nan], 'TBD.2': [nan, nan, nan], 'TimeStamp': ['2016/06/08 17:19:53', '2016/06/08 17:19:54', '2016/06/08 17:19:54'], 'Value': [0.062941999999999998, 0.062941999999999998, 0.062941999999999998]})
df['TimeStamp'] = pd.to_datetime(df['TimeStamp']).dt.strftime('%m/%d/%Y %H:%M:%S')
print(df)

yields

   TBD  TBD.1  TBD.2            TimeStamp     Value
0 NaN NaN NaN 06/08/2016 17:19:53 0.062942
1 NaN NaN NaN 06/08/2016 17:19:54 0.062942
2 NaN NaN NaN 06/08/2016 17:19:54 0.062942

Since you want to convert a column of strings to another (different) column of strings, you could also use the vectorized str.replace method:

import numpy as np
import pandas as pd
nan = np.nan
df = pd.DataFrame({'TBD': [nan, nan, nan], 'TBD.1': [nan, nan, nan], 'TBD.2': [nan, nan, nan], 'TimeStamp': ['2016/06/08 17:19:53', '2016/06/08 17:19:54', '2016/06/08 17:19:54'], 'Value': [0.062941999999999998, 0.062941999999999998, 0.062941999999999998]})
df['TimeStamp'] = df['TimeStamp'].str.replace(r'(\d+)/(\d+)/(\d+)(.*)', r'\2/\3/\1\4')
print(df)

since

In [32]: df['TimeStamp'].str.replace(r'(\d+)/(\d+)/(\d+)(.*)', r'\2/\3/\1\4')
Out[32]:
0 06/08/2016 17:19:53
1 06/08/2016 17:19:54
2 06/08/2016 17:19:54
Name: TimeStamp, dtype: object

This uses regex to rearrange pieces of the string without first parsing the
string as a date
. This is faster than the first method (mainly because it skips
the parsing step), but it also has the disadvantage of not checking that the
date strings are valid dates.



Related Topics



Leave a reply



Submit