I have this code but it displays first 3 letters of month in english. How can I change it to spanish?
if (secondsPast > 86400) {
var date = new Date(timestamp);
var currentDate = new Date(now);
var day = date.getDate();
var month = date.toDateString().match(/ [a-zA-Z]*/)[0].replace(' ', '');
var year = date.getFullYear() == currentDate.getFullYear() ? '' : ', ' + date.getFullYear();
return month + ' ' + day + ' ' + year;
}
You can use toLocaleDateString().
The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.
Please read more about it at moz wiki
Example:
var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('es-ES', options));
In PHP:
From the DateTime format page:
This method does not use locales. All output is in English.
If you need locales look into strftime Example:
setlocale(LC_ALL,"es_ES");
$string = "24/11/2014";
$date = DateTime::createFromFormat("d/m/Y", $string);
echo strftime("%A",$date->getTimestamp());
Related
I want to convert string date 2020-06-21T10:15:00Z into 21-06-2020 10:15?
I did it like splitting on two parts and remove last 4 characters from the time:
const newDate = date.split('T');
const time = newDate.length >= 1 ? newDate[1].slice(3, -1) : '';
I am looking for some better solution?
Since your input string has all the necessary parts, you may break it into pieces (e.g. using String.prototype.split()) and build up anew in desired order and with necessary delimiters:
const dateStr = '2020-06-21T10:15:00Z',
[yyyy,mm,dd,hh,mi] = dateStr.split(/[/:\-T]/)
console.log(`${dd}-${mm}-${yyyy} ${hh}:${mi}`)
.as-console-wrapper{min-height:100%;}
You can format a
const str = "2020-06-21T10:15:00Z";
const date = new Date(str);
var options = {year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric'};
console.log(date.toLocaleDateString('UTC', options));
date string using toLocaleDateString.
Try this :
<script>
function myFunction() {
var oldDate = Date.parse("2020-06-21T10:15:00Z");
var newDate = formatDate(new Date(d));
console.log(newDate)
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
hour = d.getHours();
minutes = d.getMinutes();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-') + " " + [hour,minutes].join(":");
}
</script>
try this :)
document.getElementById(' ').innerHTML = datum.toLocaleString('de-DE');
You can use the dateFormat
const mydate = new Date("2020-06-21T10:15:00Z");
console.log(dateFormat(mydate, "dd-mm-yyyy hh:MM"));
This question already has answers here:
jQuery date formatting
(24 answers)
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
When using this method, my time is returning, the values with month name, time zone and so on.
It's returning as follows: newDate = Mon Sep 02 2019 12:00:00 GMT-0300 (Brasilia Standard Time)
How would I return the format dd / MM / YYYY - hh / MM
sistema.conversao = {
converterParaDate: function (dataPtbr) {
//data virá em formato pt-br dd/mm/aaaa hh:mm
var arrDataHora = dataPtbr.split(" "); //separar a data dos minutos
var data = arrDataHora[0];
var arrHora = [];
if (arrDataHora.length > 1)
arrHora = arrDataHora[1].split(":");
var dia, mes, ano;
var arrData = data.split("/");
day= parseInt(arrData[0]);
mouth= parseInt(arrData[1]) - 1;
year= parseInt(arrData[2]);
var hour= 0, minute= 0, second= 0;
if (arrHora && arrHora.length > 0) {
hora = arrHora[0];
minuto = arrHora[1]
}
var newDate = new Date(year, mouth, day, hour, minute, second)
return newDate;
}
}
You need to separate every part of the Date object you just created and then rearrange it in any way you need it.
var day = newDate.getDate();
var month = newDate.getMonth();
var year = newDate.getFullYear();
var hours = newDate.getHours();
var minutes = newDate.getMinutes();
var formatDate = day + "/" + month + "/" + year + " - " + hours + "/" + minutes;
return formatDate;
EDIT:
Read more about Date methods: https://www.w3schools.com/js/js_date_methods.asp
Another option would be to use the native JS method toLocaleDateString() to do the formatting. It's easy to change the options to produce different date formatting requirements.
var date = new Date();
var options = {
day: 'numeric',
month: 'numeric',
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: false
};
var newDate = date.toLocaleDateString('en-US', options).replace(', ', ' - ').replace(':', '/');
console.log(newDate);
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
I am just trying to get date and time in the format below. It just seems very hard and complicated in JS.
2019-06-27 01:06:34.947
British time, date, hour minutes and seconds are the most important, milliseconds not essential.
Whenever I try, I get the time in UTC, I also do not need PM/AM etc shown.
var today = new Date().toLocaleDateString(undefined, {
day: '2-digit',
month: '2-digit',
year: 'numeric'
//hour: '2-digit',
//minute: '2-digit',
//second: '2-digit'
})
console.log('today', today)
var time = new Date().toLocaleTimeString(undefined, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
console.log('time', time)
//var date = new Date();
//var timestamp = date.getTime();
var mytime = today + " " + time;
console.log('mytime', mytime)
//var tt = new Date().toLocaleString().replace(",","").replace(/:.. /," ");
var currentdate = new Date();
var datetime = currentdate.getDate() + "/" +
(currentdate.getMonth() + 1) + "/" +
currentdate.getFullYear() +
currentdate.getHours() + ":" +
currentdate.getMinutes() + ":" +
currentdate.getSeconds();
console.log('datetime', datetime)
X = new Date().toLocaleDateString();
Y = new Date().toLocaleTimeString('en-GB', {
hour: "numeric",
minute: "numeric"
});
mynew = X + " " + Y;
console.log('mynew', mynew)
I expect to see 2019-06-27 01:06:34.947 or 27-06-2019 01:06:34.947
I'd say your best option to format a local Date instance as YYYY-mm-DD HH:MM:SS would be to build the string yourself
const today = new Date()
const formatted =
`${
today.getFullYear()
}-${
String(today.getMonth()+1).padStart(2, '0')
}-${
String(today.getDay()).padStart(2, '0')
} ${
String(today.getHours()).padStart(2, '0')
}:${
String(today.getMinutes()).padStart(2, '0')
}:${
String(today.getSeconds()).padStart(2, '0')
}`
// this just displays it
document.querySelector('pre').textContent = formatted
<pre></pre>
Libraries like Moment.js make this sort of thing much easier.
moment().format('YYYY-MM-DD HH:mm:ss')
See https://momentjs.com/docs/#/displaying/
How to get the start of the month in date format e.g. 01-05-2017?
I have already seen
Get first and last date of current month with javascript or jquery
If I understand correctly toLocaleString() might do what you want.
For example:
lastDay.toLocaleString('en-GB', {day: 'numeric', month: '2-digit', year: 'numeric'});
For more info (MDN)
Replace locale with any that suits your desired formatting.
After getting the date we need to convert it to desired string format.
01 is the day and may be a constant since every beginning of the month starts from 1.
getMonth returns number of the month starting from 0 so we need a little function to format it.
var date = new Date();
var startDate = new Date(date.getFullYear(), date.getMonth(), 1);
var startDateString = '01-' + fotmatMonth(startDate.getMonth()) + '-' + startDate.getFullYear();
console.log(startDateString);
function fotmatMonth(month) {
month++;
return month < 10 ? '0' + month : month;
}
var date = new Date();
console.log(getStartOfMonthDateAsString(date));
function getStartOfMonthDateAsString() {
function zerosPad(number, numOfZeros) {
var zero = numOfZeros - number.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + number;
}
var day = zerosPad(1, 2);
var month = zerosPad((date.getMonth() + 1), 2);
var year = date.getFullYear();
return day + '-' + month + '-' + year;
}
i've tried to do this :
var curr = new Date;
var first = curr.getDate() - curr.getDay();
var last = first + 7;
var firstday = new Date(curr.setDate(first + 1)).toUTCString();
var lastday = new Date(curr.setDate(last)).toUTCString();
But i get firstday = "Mon, 18 Jan 2016 09:14:44 GMT" and
lastday = "Sun, 24 Jan 2016 09:14:44 GMT". How can i use italian name of the day and format DD/MM as "Lunedì 10/01" (Monday 10 of January in english).
Thanks
Cris
Without having to use external libraries, you want to use the toLocaleString() function.
var options = {'weekday': 'long', 'month': '2-digit', 'day': '2-digit'};
var date = new Date().toLocaleString('it-IT', options);
document.write(date)
Reference with all the possible options
Use moment.js for that
moment.locale('it');
document.write(moment().format('dddd DD/MM'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/locale/it.js"></script>
hi you can do it by using moment.js ,By default, Moment.js comes with English locale strings. If you need other locales, you can load them into Moment.js like this:
moment.locale('it');
var currentDate = moment();
//fist
alert(moment().format('dddd, MMMM Do YYYY, h:mm:ss'));
//last
alert(currentDate.add(7, 'days').format('dddd, MMMM Do YYYY, h:mm:ss'));
this a working demo
with this approach you can craft every custom format:
function italianTimeFormat (dateUTC) {
if (dateUTC) {
let jsDateFormat = new Date(dateUTC)
let fullStringTime = {
day: Number(jsDateFormat.getDate() < 10) ? '0' + jsDateFormat.getDate() : jsDateFormat.getDate(),
month: Number((jsDateFormat.getMonth() + 1)) < 10 ? '0' + (jsDateFormat.getMonth() + 1) : (jsDateFormat.getMonth() + 1),
year: jsDateFormat.getFullYear(),
hours: Number(jsDateFormat.getHours()) < 10 ? '0' + jsDateFormat.getHours() : jsDateFormat.getHours(),
minutes: Number(jsDateFormat.getMinutes()) < 10 ? '0' + jsDateFormat.getMinutes() : jsDateFormat.getMinutes()
}
return fullStringTime.day + '/' + fullStringTime.month + '/' + fullStringTime.year + ' ' +
fullStringTime.hours + ':' + fullStringTime.minutes
}
return null
}
let today = Date.now();
document.write(italianTimeFormat(today))
I hope i've been helpful for someone