Date in a Url Dd/Mm/Yyyy

Date in a URL dd/mm/yyyy

When using strotime() you need to make sure you are using a valid datetime format. Otherwise strtotime() will return false or give you an unexpected value.

Dates that use XX/XX/XXXX format are assumed to be in US format which means the first two digits represent the month, the next two digits represent the day of month, and the last four digits represent the year. When dashes are used, the dates are assumed to be in European format. For example:

04/18/2017 = April 18, 2017
12/18/2017 = December 18, 2017
18-04-2017 = April 18, 2017
18-12-2017 = December 18, 2017

If you accidentally switch the day and month strtotime() will return false as the date is invalid.

18/04/2017 // error
18/12/2017 // error
04-18-2018 // error
12-18-2017 // error

The above examples are straight forward. But you can run into issues when the dates can be ambigous. For example:

04/12/2017 = April 12, 2017
12/04/2017 = December 4, 2017
04-12-2017 = December 4, 2017
12-04-2017 = April 12, 2017

In the above examples by switching the day and month we still get valid dates which can cause unexpected results in your application. To solve these potential issues it is recommended to use DateTime::createFromFormat() to parse the date ad return a DateTime() object from which you can get a Unix Timestamp, convert the date into another format, or use it to compare to other DateTime objects.

// Parse US date format
$date1 = DateTime::createFromFormat('m/d/Y', '04/18/2017');

// Get Unix timestamp of 1493581268
$timestamp = $date1->getTimestamp();

// Parse European date format
$date2 = DateTime::createFromFormat('d-m-Y', ''18-04-2017);

// Get MySQL format (ISO-8601) of 2017-04-18
$mysqlDate = $date2->format('Y-m-d');

See also:

  • Compare DateTime objects with comparison operators in PHP

For your specific case, the follow code will work:

$date = $date1 = DateTime::createFromFormat('m/d/Y', '20/02/2000');
$D->query = $date->format('Y-m-d'); // 2000-02-20

How to fix a Date format that changes in my GET URL

Split the date with - and now join again according to your desired structure.

Here i swapped element of index 0 and 1 as you just wanted to interchange month and date.

let str = `01-12-1994`let dateArray = str.split('-')let desiredDate = dateArray[1]+'-' + dateArray[0] + '-' + dateArray[2]
console.log(desiredDate)

Angular get dates from last 24 hours in format dd/MM/yyyy HH:mm

    // getting new date
let today = new Date();

// getting previous date
let yesterday = new Date(today.getTime() - (24*60*60*1000));

// formatting the date
let latest_date = this.datePipe.transform(yesterday, 'dd-MM-yyyy');

I have created a stackblitz link for you.Click here

strtotime for DD/MM/YYYY not working properly

The DateTime class can be used in situations like this - it has the useful method createFromFormat

    $date='10/09/19';   //dd/mm/yy
$new=DateTime::createFromFormat('d/m/y', $date )->format('Y/m/d');
echo $new; //2019/09/10

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

I hope this is what you want:

const today = new Date();
const yyyy = today.getFullYear();
let mm = today.getMonth() + 1; // Months start at 0!
let dd = today.getDate();

if (dd < 10) dd = '0' + dd;
if (mm < 10) mm = '0' + mm;

const formattedToday = dd + '/' + mm + '/' + yyyy;

document.getElementById('DATE').value = formattedToday;

How do I get the current date in JavaScript?

Web API - How to receive in controller DateTime ('dd/MM/yyyy') as Url parameter?

I manage to solve my problem using Model binding as suggested by @Jakotheshadows and @Amy.

I used the code from this answer about ModelBinders in Web Api with a few tweaks from this answer (it's in portuguese, but the code is clear).

So my code right now:

using System;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;

namespace Site.Services
{
public class DateTimeModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
ValidateBindingContext(bindingContext);

if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName) ||
!CanBindType(bindingContext.ModelType))
{
return false;
}

var modelName = bindingContext.ModelName;
var attemptedValue = bindingContext.ValueProvider
.GetValue(modelName).AttemptedValue;

try
{
bindingContext.Model = DateTime.Parse(attemptedValue);
}
catch (FormatException e)
{
bindingContext.ModelState.AddModelError(modelName, e);
}

return true;
}

private static void ValidateBindingContext(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}

if (bindingContext.ModelMetadata == null)
{
throw new ArgumentException("ModelMetadata cannot be null", "bindingContext");
}
}

public static bool CanBindType(Type modelType)
{
return modelType == typeof(DateTime) || modelType == typeof(DateTime?);
}
}
}

I used try and DateTime.Parse as suggested in the second link, because the first always throwed an exception even with try and catch.

The ModelBinderProvider I used as he suggested:

using System;
using System.Web.Http;
using System.Web.Http.ModelBinding;

namespace Site.Services
{
public class DateTimeModelBinderProvider : ModelBinderProvider
{
readonly DateTimeModelBinder binder = new DateTimeModelBinder();

public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
{
if (DateTimeModelBinder.CanBindType(modelType))
{
return binder;
}

return null;
}
}
}

And I configure as suggested here (also an answer for the first link), but in my WebApiConfig.cs (didn't work in Global.asax), like this:

using Site.Services;
using System;
using System.Web.Http;

namespace Site
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.BindParameter(typeof(DateTime), new DateTimeModelBinder());
config.BindParameter(typeof(DateTime?), new DateTimeModelBinder());

//Rest of my code
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}

I think the globalization of the Web.config, the uiCulture and culture must be set to the culture you want and enableClientBasedCulture be set as true as suggest here, but I'm not sure because I didn't want to change the code to test it.

How to check if a string is a legal dd/mm/yyyy date?

Edit: exact solution below

You could do something like this, but with a more accurate algorithm for day validation:

function testDate(str) {
var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
if(t === null)
return false;
var d = +t[1], m = +t[2], y = +t[3];

// Below should be a more acurate algorithm
if(m >= 1 && m <= 12 && d >= 1 && d <= 31) {
return true;
}

return false;
}

http://jsfiddle.net/aMWtj/

Date validation alg.: http://www.eee.hiflyers.co.uk/ProgPrac/DateValidation-algorithm.pdf

Exact solution: function that returns a parsed date or null, depending exactly on your requirements.

function parseDate(str) {
var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
if(t !== null){
var d = +t[1], m = +t[2], y = +t[3];
var date = new Date(y, m - 1, d);
if(date.getFullYear() === y && date.getMonth() === m - 1) {
return date;
}
}

return null;
}

http://jsfiddle.net/aMWtj/2/

In case you need the function to return true/false and for a yyyy/mm/dd format

function IsValidDate(pText) {
var isValid = false ;
var t = pText.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);

if (t !== null) {
var y = +t[1], m = +t[2], d = +t[3];
var date = new Date(y, m - 1, d);

isValid = (date.getFullYear() === y && date.getMonth() === m - 1) ;
}

return isValid ;
}


Related Topics



Leave a reply



Submit