Extract the DateTime format from a given date string

extract date from string java
how to extract date from string in python
how to convert string to a particular date format in java
how to get month and year from string date in java
how to get only date from timestamp in java
how to extract date from datetime in java
java date format
change string date format in java

I was wondering if there was a way to extract the DateTime format from a given date string. In C# For example:

var dateString = "12/10/2018";
var format = GetDateFormat(dateString);

and then the format will be like 'long date time' or something.

Via hard-coding or reflection (shown below) you could retrieve the value of all properties of the DateTimeFormatInfo class whose name end with "Pattern", then attempt parsing using those patterns and see which ones are successful. You're then limited to the patterns provided by that class and whichever culture(s) you choose to use, though.

DateTimeFormatInfo formatInfo = DateTimeFormatInfo.CurrentInfo;
IEnumerable<PropertyInfo> patternProperties = formatInfo.GetType().GetProperties()
    .Where(property => property.Name.EndsWith("Pattern"));

foreach (PropertyInfo patternProperty in patternProperties)
{
    string pattern = (string) patternProperty.GetValue(formatInfo);
    bool wasParsed = DateTime.TryParseExact(dateString, pattern, formatInfo, DateTimeStyles.None, out DateTime _);

    Console.WriteLine($"{patternProperty.Name} (\"{pattern}\"): {wasParsed}");
}

On my system (en-US) the above code produces the following output:

FullDateTimePattern ("dddd, MMMM d, yyyy h:mm:ss tt"): False
LongDatePattern ("dddd, MMMM d, yyyy"): False
LongTimePattern ("h:mm:ss tt"): False
MonthDayPattern ("MMMM d"): False
RFC1123Pattern ("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"): False
ShortDatePattern ("M/d/yyyy"): True
ShortTimePattern ("h:mm tt"): False
SortableDateTimePattern ("yyyy'-'MM'-'dd'T'HH':'mm':'ss"): False
UniversalSortableDateTimePattern ("yyyy'-'MM'-'dd HH':'mm':'ss'Z'"): False
YearMonthPattern ("MMMM yyyy"): False

Java exercises: Extract date, time from the date string, Java DateTime, Calendar: Exercise-35 with Solution. Write a Java program to extract date, time from the date string. Sample Solution:. You can simply use a regular expression to extract the date and "datetime.datetime.strptime" to parse the date. For example, If you have the date in a string in the format YYYY-MM-DD, you can use the following code to extract and parse this date, This will give the output: 2018-12-10

You could try DateTime.TryParseExact with a set of predefined formats. Those that match will be the format(s) you are looking for.

DateTime.ParseExact Method (System), Converts the specified string representation of a date and time to its DateTime equivalent using the specified array of formats, culture-specific format information​,  In this article, you will learn to create a datetime object from a string (with the help of examples). For that, we use Python's strptime() method. Any string representing date and time can be converted to datetime object by using a corresponding format code equivalent to the string.

There's no built-in function or anything, but you could write one yourself. Here is a short example that checks for three possible formats; you can add as many more as you like just by adding to the list.

If you need to support unusual formats (e.g. formats that can't be auto-detected by DateTime.Parse() then you may need a slightly different solution that tests the input using DateTime.ParseExact(), like BACON's answer.

public class Program
{
    //Returns a string indicating the format of the input, or null if could not be detected
    public static string GetDateTimeFormatCode(string dateTimeString)
    {
        //Parse the input
        DateTime dateTime;
        if (!DateTime.TryParse(dateTimeString, out dateTime)) return null;

        return
        (
            new string[]
            {
                "M/d/yyyy",
                "d MMM yyyy",
                "d MMMM yyyy",
                "dddd MMMM d yyyy"
            }
        )
        .Where( c => dateTime.ToString(c) == dateTimeString )
        .FirstOrDefault();
    }

    public static void Main()
    {
        var tests = new List<string>
        {
            @"21 May 2018",
            @"6/21/2018",
            @"Monday May 21 2018"
        };

        foreach (var t in tests)
        {
            Console.WriteLine("Input '{0}' uses format '{1}'", t, GetDateTimeFormatCode(t) ?? "?");
        }

    }
}

Output:

Input '21 May 2018' uses format 'd MMM yyyy'
Input '6/21/2018' uses format 'M/d/yyyy'
Input 'Monday May 21 2018' uses format 'dddd MMMM d yyyy'

Code on DotNetFiddle

Java Date - parse, format and conversion, Learn to create new date, get current date, parse date to string or format Date object using java.util.Date class. By Lokesh Gupta | Filed Under: Java Date/​Time. I have a string Certificate Expiration Date: 2/23/2022 7:39 AM and from this I want to extract the date only in the format Wednesday, February 23, 2022 7:39:23 AM and store it in a variable in date format. Any script to achieve this will be helpful

How to extract date from a string in Python?, You need to know the format of date that can be there in the string in to extract the date and "datetime.datetime.strptime" to parse the date. To extract only date from a list of datetime cells in Excel worksheet, the INT, TRUNC and DATE functions can help you to deal with this job quickly and easily. Normally, in Excel, the datetime is recognized as serial number, the integer part is a date serial number, and the fractional portion is time serial number.

[Solved] How to extract date from given string?, One way is to use DateTime.TryParse and then the Date property. Consider the following. Hide Copy Code. System.DateTime a; if(System. A date and time format string defines the text representation of a DateTime or DateTimeOffset value that results from a formatting operation. It can also define the representation of a date and time value that is required in a parsing operation in order to successfully convert the string to a date and time.

How to extract date elements and change a date value to a , in the Transform node to extract elements from a date data type field and. field and format a field date field to a string field with a specified format. The Python datetime module provides a set of operators to transform date  To extract the abbreviated weekday name for a specific culture, call the date and time value's DateTime.ToString(String, IFormatProvider) or DateTimeOffset.ToString(String, IFormatProvider) instance method. Pass the string "ddd" as the format parameter.

Comments
  • There is none, at least not built-in. Why? Because 12/10/2018 can be dd/MM/yyyy and MM/dd/yyyy
  • This wouldn't work, since there are ambiguous possibilities
  • The ambiguity is part of the question, not the answer ;)