Symfony, how to get localized date - symfony

most likely a silly question, but I do not see how to do.
Within a controller, I need to use $myObj->getData()->format('d-M-Y'), and I wish to get a localized string too (in italian instead than in english).
Within a twig template, I get it by {{ myobj.data|localizeddate('long', 'none', app.request.locale ) }}, but I do not know a similar trick for the former case.
Yes, I found how to do (thanks to ccKep):
$cal = IntlCalendar::fromDateTime($oldObj->getData()->format('d-M-Y')." Europe/Rome");
$newObj->setField("my date is ". IntlDateFormatter::formatObject($cal, "d MMMM YYYY", 'it_IT')."");

In controller you may use Intl. For example:
$intl = new \IntlDateFormatter($request->getLocale(), \IntlDateFormatter::LONG, \IntlDateFormatter::NONE, null, null, 'd-LLL-y');
$date = $intl->format(new \DateTime('now'));

Related

Changing the Session Languge leads to "java.text.ParseException: Unparseable date

whenever I'm defining the timeframe being in German session language after changing to English lang. session (and vice versa) I'm getting the:
java.text.ParseException: Unparseable date: "10.10.2018"
Here is the fragment:
Date startDateFormatted = DateUtils.convertDateToMinusDayNumber(cal, dayRange);
Date endDateFormatted = new Date();
if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate))
{
try
{
String datePattern = getLocalizedString("dd.MM.yyyy"); //
startDateFormatted = new SimpleDateFormat(datePattern).parse(startDate); // exception is throwing on this line
endDateFormatted = new SimpleDateFormat(datePattern).parse(endDate);
}
catch (final Exception e)
{
LOG.error(ERROR_DATE_PARSING, e);
}
}
java.time
I recommend you use java.time, the modern Java date and time API, for your date work.
String datePattern = "dd.MM.uuuu";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(datePattern);
String startDateString = "10.10.2018";
LocalDate startDate = LocalDate.parse(startDateString, dateFormatter);
System.out.println(startDate);
Output:
2018-10-10
If you want to support different date formats for different locales, let Java handle that part for you:
String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.MEDIUM, null, IsoChronology.INSTANCE, Locale.GERMAN);
German locale works with your example string of 10.10.2018. For UK locale, for example, a string like 10 Oct 2018 would be required instead, as Britons would typically expect.
What went wrong in your code?
We cannot tell from the information and code that you have provided exactly what happened. A couple of good guesses are:
As Arvind Kumar Avinash said in a comment, getLocalizedString() may be causing trouble. You may print datePattern to check. Localization is something you do to strings that you display to the user. Trying to localize a format pattern string for a formatter is probably plain wrong, so you should leave out that method call. That the error occurs when changing language seems to support this possibility.
There may be unexpected non-printing characters in your string. One way to check would be to print startDate.length(). If the length is greater than 10, there are more characters than the 10 chars in 10.10.2018.
Link
Oracle tutorial: Date Time explaining how to use java.time.

moment.js will not parse UK format date even when setting the locale

Quite simply, this is my code:
http://jsfiddle.net/NibblyPig/k9zb4ysp/
moment.locale('en-GB');
var d = moment('22/12/2019');
alert(d);
I would expect this to parse, however it says invalid date.
I have referenced moment.js and the locale/en-gb.js
I'm writing a global control so the date may come in in a variety of formats.
If I put in a variety of American dates they all work, for example 12/12/2019, 12/12/2019 23:04 etc.
However the locale command does not appear to do anything and I cannot get a single date to parse. What am I doing wrong?
You need to pass the format as the second argument for moment(), as discussed here:
moment.locale('en-GB');
var d = moment('22/12/2019', 'DD/MM/YYYY');
alert(d);
https://jsfiddle.net/a4gu6kfz/
From the docs:
If you know the format of an input string, you can use that to parse a
moment.
moment("12-25-1995", "MM-DD-YYYY");
I think that there is no need to write your own complex logic to parse your input, you can use moment(String, String) (or moment(String, String[], String, Boolean)), as suggested by Thales Minussi's answer.
moment(String) is the good choice only if your input is in ISO 8601 or RFC 2822 compliant form.
In your case, you can probably use Localized formats listed in the format section of the docs. If you have a list of possible formats, I think that the best choice is tho use moment(String, String[]).
Please note that, by default: Moment's parser is very forgiving, so using default Forgiving Mode will handle "any" character as separator.
Here a live sample:
moment.locale('en-GB');
['22/12/2019', '22/12/2019 15:00',
'22-12-2019', '22-12-2019 15:00',
'1-3-2019', '1-12-2019', '22-1-2019'
].forEach((elem) => {
var d = moment(elem, 'L LT');
console.log(d.format());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/en-gb.js"></script>
Still hoping there's a nice moment js way to do this but in the meantime I just bashed this together. Pretty nasty and it will probably go wrong in 80 years or so.
http://jsfiddle.net/NibblyPig/k9zb4ysp/22/
var a = "23/03/19 12:42:21.123";
var datePart = a.substring(0, a.indexOf(" "));
var timePart = a.substring(a.indexOf(" ") + 1);
var dateParts = datePart.split("/");
if (dateParts[0].length == 1) dateParts[0] = "0" + dateParts[0];
if (dateParts[1].length == 1) dateParts[1] = "0" + dateParts[1];
if (dateParts[2].length == 2) {
var threshold = parseInt(new Date().getFullYear().toString().substring(2)) + 10;
if (parseFloat(dateParts[2]) > threshold ) {
dateParts[2] = "19" + dateParts[2];
}
else
{
dateParts[2] = "20" + dateParts[2];
}
}
alert (parseFloat(dateParts[2] + dateParts[1] + dateParts[0] + timePart.replace(/:/g, "").replace(/\./g, "")));
This won't solve every usecase, but in your specific example if you want just a simple date (with no time component) auto-parsed in UK format you can just use the 'L' format string having set the locale to 'en-GB'
Your example with this change (your jsfiddle also)
moment.locale('en-GB');
// just pass 'L' i.e. local date format as a parsing format here
var d = moment('22/12/2019', 'L');
alert(d);
It's quite nice because you get the auto parsing of various formats you wanted for free. For instance this works just the same:
var d = moment('22-12-2019', 'L');
You can return a date using moment.js in a desired format -
return moment(aDateVar).format('DD/MM/YYYY');

Drupal7 format_date

Somebody could help me to how to change string date with format_date function.
Here is my code$datesql = format_date("2014-04-02 11:11:31", 'custom', 'Y-m-d');
drupal_set_message(t('date '.$datesql));
I suppose drupal to show this message "date 2014-04-02", but drupal just show the message "date", not $datesql. What is wrong in my code.
Thanks
Function "format_date" expects first parameter to be a timestamp, not a string. Try to wrap this first parameter with "strtotime" function and you will get a better result.
PS: do not include a variable in the first parameter of the "t" function. This could result in a lot of translatable strings. Pass it in the second parameter with "#myvar" as key. Check the "t" function documentation for more details.
try this
$date = new DateTime('2014-04-02 11:11:31');
$da = $date->format('Y-m-d H:i:s');
drupal_set_message('date '.$da,'status');
format_date() is use a covert a date in drupal created date not a convert a custom date
format_date($node->created, 'custom', 'Y-m-d');

Regex verification correct birth date and check age

I need a regex which takes the string YYYY-MM-DD-XXXX (The last 4 are just for purpose of gender/area) It's mostly important to check the first 8 Digits for a valid birth date.
So far i have this:
/^([0-9]{4})\-([0-9]{2})\-([0-9]{2})\-([0-9]{4})$/
Also i want to check so the input age is at least 18 years old. Would appreciate if somone had some input on how to achieve this.
Edit: The regex above was tested in JS, but should work fine in ASP as well?
I have changed your regex a bit to make it look more authentic
^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$
years like 3012 will not pass.
Now you want to find whether a person is 18 years or not.
One approach could be to find the difference between the years of dates provided like this
var str = '1990-09-12-5555';
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var year_now = new Date().getFullYear();
console.log(year_now-res[1]);
a second approach will be more precise one :
var str = '1990-09-12-5555';
var res = /^([1-2]\d{3})\-([0-1][1-9])\-([0-3][0-9])\-([0-9]{4})$/.exec(str);
var todays_date = new Date();
var birth_date = new Date(res[1],res[2],res[3]);
console.log(todays_date-birth_date);
will output the result in milliseconds. You can do the math to convert it into year
Cheers , Hope that helps !
I suggest using moment.js which provides an easy to use method for doing this.
interactive demo
function validate(date){
var eighteenYearsAgo = moment().subtract("years", 18);
var birthday = moment(date);
if (!birthday.isValid()) {
return "invalid date";
}
else if (eighteenYearsAgo.isAfter(birthday)) {
return "okay, you're good";
}
else {
return "sorry, no";
}
}
To include moment in your page, you can use CDNJS:
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>
Source
The following will match any year with a valid day/month combination, but won't do validation such as checking you've not entered 31 days for February.
^[0-9]{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])\-[0-9]{4}$
Not sure exactly what you're trying to achieve but I'd suggest using a date library for this sort of thing. You could return a message to the user somehow if the entered date fails to parse into an object.
In order to do age validation, you will certainly need to use a library so a regex should only be used for date validation purposes

google charts datetime type

Is it possible to use literal strings when instantiating a datetime type? (If no, skip) If so, does the - need to be a /? If that doesn't matter, please tell me what's wrong with this:
var data = new google.visualization.DataTable({cols:[{label: 'date', type: 'datetime'},
{label: 'power', type: 'number'}], rows: [{c: [{v:2007/12/01 00:12:00},{v:0}]},
{c: [{v:2007/12/01 01:12:00},{v:101}]}, {c: [{v:2007/12/01 02:12:00},{v:201}]},
{c: [{v:2007/12/01 03:12:00},{v:302}]}]});
(I already tried quoting literal datetimes.)
-Shawn
You might have to put it in Epoch format. try something like this
new Date("#epoch_seconds_go_here");
Here is the link that might help you

Resources