Converting dd/mm/yyyy formatted string to Datetime
You need to use DateTime.ParseExact
with format "dd/MM/yyyy"
DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);
Its safer if you use d/M/yyyy
for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.
Your date format day/Month/Year
might be an acceptable date format for some cultures. For example for Canadian Culture en-CA
DateTime.Parse
would work like:
DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));
Or
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture
Both the above lines would work because the the string's format is acceptable for en-CA
culture. Since you are not supplying any culture to your DateTime.Parse
call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.
Another method for parsing is using DateTime.TryParseExact
DateTime dt;
if (DateTime.TryParseExact("24/01/2013",
"d/M/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
//valid date
}
else
{
//invalid date
}
The TryParse
group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool
value indicating success or failure in parsing.
Notice that I have used single d
and M
for day and month respectively. Single d
and M
works for both single/double digits day and month. So for the format d/M/yyyy
valid values could be:
- "24/01/2013"
- "24/1/2013"
- "4/12/2013" //4 December 2013
- "04/12/2013"
For further reading you should see: Custom Date and Time Format Strings
how to format String to Date with format dd-mm-yyyy in java
tl;dr
LocalDate
.parse( "2022-05-12" )
.format(
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
12-05-2022
java.time
Use modern java.time classes. Never use the terrible Date
, Calendar
, SimpleDateFormat
classes.
ISO 8601
Your input conforms to ISO 8601 standard format used by default in the java.time classes for parsing/generating text. So no need to specify a formatting pattern.
LocalDate
Parse your date-only input as a date-only object, a LocalDate
.
String input = "2022-05-12" ;
LocalDate ld = LocalDate.parse( input ) ;
To generate text in your desired format, specify a formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
String output = ld.format( f ) ;
Rather than hardcode a particular pattern, I suggest learning to automatically localize using DateTimeFormatter.ofLocalizedDate
.
All this has been covered many many times already on Stack Overflow. Always search thoroughly before posting. Search to learn more.
How to convert dd/mm/yyyy string into JavaScript Date object?
MM/DD/YYYY format
If you have the MM/DD/YYYY
format which is default for JavaScript, you can simply pass your string to Date(string)
constructor. It will parse it for you.
var dateString = "10/23/2015"; // Oct 23
var dateObject = new Date(dateString);
document.body.innerHTML = dateObject.toString();
Convert string dd/mm/yy to datetime
Your code seems ok, but also you can convert a string into datetime like below
DateTime d = DateTime.ParseExact("11/02/2016", "dd/MM/yyyy", CultureInfo.InvariantCulture);
return d;
if you have string as dd/MM/yy
format and need to convert it as dd/MM/yyyy
fomat datetime then you can do like this
DateTime temp = DateTime.ParseExact("11/02/16", "dd/MM/yy", CultureInfo.InvariantCulture);
DateTime d = DateTime.ParseExact(temp.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
return d
Convert dd-mm-yyyy string to date
Split on "-"
Parse the string into the parts you need:
var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
Use regex
var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))
Why not use regex?
Because you know you'll be working on a string made up of three parts, separated by hyphens.
However, if you were looking for that same string within another string, regex would be the way to go.
Reuse
Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:
function toDate(dateStr) {
var parts = dateStr.split("-")
return new Date(parts[2], parts[1] - 1, parts[0])
}
Using as:
var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)
Or if you don't mind jQuery in your function:
function toDate(selector) {
var from = $(selector).val().split("-")
return new Date(from[2], from[1] - 1, from[0])
}
Using as:
var f = toDate("#datepicker")
var t = toDate("#datepickertwo")
Modern JavaScript
If you're able to use more modern JS, array destructuring is a nice touch also:
const toDate = (dateStr) => {
const [day, month, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}
How to convert a dd/mm/yyyy string to a date in Javascript
You need to enter the date in the format of "01/28/2019"
for it to be a valid date string which can be parsed. You can do this using .split()
to manipulate the string around.
See example below:
var date1 = "28/01/2019".split('/')
var newDate = date1[1] + '/' +date1[0] +'/' +date1[2];
var date = new Date(newDate);
console.log(date);
How to convert a dd.MM.yyyy string to a Date object
If you absolutely have to have it in that format, you can rearrange it quick before using the date object as it expects a certain format..
Something like this could work.
if( typeof myVar === 'string') {
let dateArr = myVar.split('.');
let myDate = new Date(dateArr[1] + '-' + dateArr[0] + '-' + dateArr[2]);
if (myDate.getTime() < this.getMinDate().getTime()) /** compare two dates */
//omitted source code
}
Convert string into mm/dd/yyyy format
It fails on the very first term of your format string, which is telling the function to treat the "16" as minutes and to look for hours, minutes, and seconds that don't exist in the input.
You have several different date formats, and so need the ParseExact() overload that accepts several different format strings:
string[] formats= {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd",
"dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"};
string converted = DateTime.ParseExact("16-05-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");
Also remember that lower case "m"s are for minutes. If you want months, you need an upper case "M". Full documentation on format strings is here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Finally, I suspect you are getting ahead of yourself on formatting the output as a string. Keep these values as DateTime objects for as long as possible, and only format to a string at the last possible moment before showing them to the user. If you really do want a string, at least stick with the ISO 8601 standard format.
Not able to convert string dd/MM/yyyy to Date dd/MM/yyyy in java
tl;dr
LocalDate.parse( "22/09/2016" , DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )
.format( DateTimeFormatter.ofPattern( "dd/MM/yyyy" ) )
Problems
- You are conflating date-time objects with strings representing date-time values. A date-time object can parse a string, and can generate a string, but the date-time object is always separate and distinct from the string. The string has a format; the date-time object does not.
- You are using troublesome old date-time classes now supplanted by the java.time classes.
- You are trying to fit a date-only value into a date-time object (square peg, round hole).
- You are being tricked by the poorly-designed
toString
method that silently applies a time zone to an internal value that has no time zone (is UTC).
Be sure to read the correct Answer by Jon Skeet.
java.time
Using the new java.time classes, specifically LocalDate
. The LocalDate
class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/yyyy" );
LocalDate ld = LocalDate.parse( "22/09/2016" , f );
Generate a String to represent that value in standard ISO 8601 format by calling toString
.
String output = ld.toString(); // 2016-09-22
Generate a String in your desired format by applying the formatter.
String output = ld.format( f );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Convert string data type date value into date format dd-mm-yyyy
This can be done by:
DECLARE @Dt VARCHAR(20) = '16-12-1997 00:00:00'
SELECT CONVERT(varchar(10), @Dt);
Is this something what you are looking for?
Related Topics
Create Frequency Tables for Multiple Factor Columns in R
How to Arrange an Arbitrary Number of Ggplots Using Grid.Arrange
Referring to Data.Table Columns by Names Saved in Variables
Convert Four Digit Year Values to Class Date
Save Plot with a Given Aspect Ratio
Put a Break in the Y-Axis of a Histogram
Reordering Factor Gives Different Results, Depending on Which Packages Are Loaded
Expand Spacing Between Tick Marks on X Axis
Rmarkdown: How to Change the Font Color
Add Line Break to Axis Labels and Ticks in Ggplot
Filling Area Under Curve Based on Value
How to Directly Select the Same Column from All Nested Lists Within a List
Download a File from Https Using Download.File()
Get All Diagonal Vectors from Matrix
Get_Map Not Passing the API Key (Http Status Was '403 Forbidden')
How to Get Ranks with No Gaps When There Are Ties Among Values