Localizing day and month in moment.js [duplicate] - javascript

This question already has answers here:
display day and month, without a year according to locale
(5 answers)
Closed 5 years ago.
How can I localize current day and month (without year) in moment.js? What I want is exactly the output of moment().format('LL') but without the year part.
Consider the following example:
moment().locale('tr').format('LL') // "1 Haziran 2017"
moment().locale('en').format('LL') // "June 1, 2017"
What I want is these:
moment().locale('tr').format('??') // "1 Haziran"
moment().locale('en').format('??') // "June 1"

For error prone solution for all supported locales, you need to remove year with .replace and check for unnecessary symbols left:
function getCurrDayAndMonth(locale) {
var today = locale.format('LL');
return today
.replace(locale.format('YYYY'), '') // remove year
.replace(/\s\s+/g, ' ')// remove double spaces, if any
.trim() // remove spaces from the start and the end
.replace(/[рг]\./, '') // remove year letter from RU/UK locales
.replace(/de$/, '') // remove year prefix from PT
.replace(/b\.$/, '') // remove year prefix from SE
.trim() // remove spaces from the start and the end
.replace(/,$/g, ''); // remove comma from the end
}
['af' , 'ar-dz', 'ar-kw', 'ar-ly', 'ar-ma', 'ar-sa', 'ar-tn', 'ar', 'az', 'be', 'bg', 'bn', 'bo', 'br', 'bs', 'ca', 'cs', 'cv', 'cy', 'da', 'de-at', 'de-ch', 'de', 'dv', 'el', 'en-au', 'en-ca', 'en-gb', 'en-ie', 'en-nz', 'eo', 'es-do', 'es', 'et', 'eu', 'fa', 'fi', 'fo', 'fr-ca', 'fr-ch', 'fr', 'fy', 'gd', 'gl', 'gom-latn', 'he', 'hi', 'hr', 'hu', 'hy-am', 'id', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'ky', 'lb', 'lo', 'lt', 'lv', 'me', 'mi', 'mk', 'ml', 'mr', 'ms-my', 'ms', 'my', 'nb', 'ne', 'nl-be', 'nl', 'nn', 'pa-in', 'pl', 'pt-br', 'pt', 'ro', 'ru', 'sd', 'se', 'si', 'sk', 'sl', 'sq', 'sr-cyrl', 'sr', 'ss', 'sv', 'sw', 'ta', 'te', 'tet', 'th', 'tl-ph', 'tlh', 'tr', 'tzl', 'tzm-latn', 'tzm', 'uk', 'ur', 'uz-latn', 'uz', 'vi', 'x-pseudo', 'yo', 'zh-cn', 'zh-hk', 'zh-tw'].forEach(localeName => {
console.log(
localeName + ':',
getCurrDayAndMonth(moment().locale(localeName)));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

Do you just want the string representation? If so, it might be easier to just trim the last 5 chars from the end of the output, like so:
var today = moment().locale('tr').format('LL') // "1 Haziran 2017"
today = today.substring(0, today.length - 5); // "1 Haziran"
This'll work for the next 8000 years, so no real need to worry about future years breaking it.
You could even do smarter regex matching, or just remove everything with ", 20XX" from the string. Depends on your uses of it though, this is more of a hacky workaround than a direct solution.

Here's an example of how it can work:
var d = moment().locale('tr');
console.log(d.format('D MMMM'));
JSFiddle: https://jsfiddle.net/webbm/wuwkwzou/

Related

How to translate date in "Date Range Picker" where month is formated as string?

I am using javascript date range picker component (https://www.daterangepicker.com/).
Localization is well handled on all levels except in one case I do not know how to correctly set it up.
On the screenshot you can see that everything is in german, except for the one marked with arrow.
This value is set by
locale: {
format: 'MMMM D, YYYY',
I do not know how I can translate the MMMM part.
Here is the whole daterangepicker code.
function ranges_locale($langcode) {
var _default_ranges = {
next_7_days: [moment(), moment().add(7, 'days')],
tomorrow: [moment().add(1, 'days'), moment().add(1, 'days')],
today: [moment(), moment()],
yesterday: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
last_7_days: [moment().subtract(6, 'days'), moment()],
last_30_days: [moment().subtract(29, 'days'), moment()],
this_month: [moment().startOf('month'), moment().endOf('month')],
last_month: [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
};
var _ranges = {
'en': {
'Next 7 Days': _default_ranges.next_7_days,
'Tomorrow': _default_ranges.tomorrow,
'Today': _default_ranges.today,
'Yesterday': _default_ranges.yesterday,
'Last 7 Days': _default_ranges.last_7_days,
'Last 30 Days': _default_ranges.last_30_days,
'This Month': _default_ranges.this_month,
'Last Month': _default_ranges.last_month,
},
'de': {
'Nächste 7 Tage': _default_ranges.next_7_days,
'Morgen': _default_ranges.tomorrow,
'Heute': _default_ranges.today,
'Gestern': _default_ranges.yesterday,
'Letzte 7 Tage': _default_ranges.last_7_days,
'Letzte 30 Tage': _default_ranges.last_30_days,
'Dieser Monat': _default_ranges.this_month,
'Letzter Monat': _default_ranges.last_month,
}
};
target.daterangepicker({
"opens": "center",
"maxSpan": {
"days": 366
},
locale: {
format: 'MMMM D, YYYY',
applyLabel: tc('Apply'),
cancelLabel: tc('Cancel'),
customRangeLabel: tc('Custom Range'),
daysOfWeek: [
tc('Su'), tc('Mo'), tc('Tu'), tc('We'), tc('Th'), tc('Fr'), tc('Sa')
],
monthNames: [
tc('January'), tc('February'), tc('March'), tc('April'), tc('May'), tc('June'), tc('July'), tc('August'), tc('September'), tc('October'), tc('November'), tc('December')
],
firstDay: 1
},
ranges: ranges_locale(currentLanguage),
"alwaysShowCalendars": true,
"startDate": target.attr('start-date'),
"endDate": target.attr('end-date'),
});
Thank you.
Date range picker is using moment under the hood so you can do some customisation to replace the english month to german month.
Play the code below to see if it can do what you want:
<html>
<head>
<script type="text/javascript" src="https://cdn.jsdelivr.net/jquery/latest/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
</head>
<body>
<input type="text" name="daterange" value="01/01/2018 - 01/15/2018" />
<script>
$(function () {
// update locale to de and customize the MMM, MMMM translation
moment.updateLocale("de", {
months : ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
monthsShort : ['Jan', 'Feb', 'März', 'Apr', 'Mai', 'Juni', 'Juli', 'Aug', 'Sept', 'Okt', 'Nov', 'Dez']
});
$('input[name="daterange"]').daterangepicker({
"opens": "center",
"maxSpan": {
"days": 366
},
locale: {
format: 'MMMM D, YYYY',
applyLabel: tc('Apply'),
cancelLabel: tc('Cancel'),
customRangeLabel: tc('Custom Range'),
daysOfWeek: [
tc('Su'), tc('Mo'), tc('Tu'), tc('We'), tc('Th'), tc('Fr'), tc('Sa')
],
monthNames: [
tc('January'), tc('February'), tc('March'), tc('April'), tc('May'), tc('June'),
tc('July'), tc('August'), tc('September'), tc('October'), tc('November'), tc('December')
],
firstDay: 1
},
// ranges: ranges_locale(currentLanguage),
"alwaysShowCalendars": true,
// "startDate": today, //target.attr('start-date'),
// "endDate": target.attr('end-date'),
});
})
const germanMapping = {
'Su': 'So',
'Mo': 'Mo',
'Tu': 'Di',
'We': 'Mi',
'Th': 'Do',
'Fr': 'Fr',
'Sa': 'Sa',
'January': 'Januar',
'February': 'Februar',
'March': 'März',
'April': 'April',
'May': 'Mai',
'June': 'Juni',
'July': 'Juli',
'August': 'August',
'September': 'September',
'October': 'Oktober',
'November': 'November',
'December': 'Dezember',
"Apply": "Anwenden",
"Cancel": "Stornieren"
}
const tc = (val) => germanMapping[val]
</script>
</body>
</html>
Since DataRangePicker manages date using moment, if you want to change bottom label language you should add this import:
import "moment/locale/de";
and the result is:
Here a codesandbox example.
I didn't find a direct solution, but a workaround.
What if you change the months with jQuery? You get somehow the current language (one way is probably with <html lang="en">) and then change the month string.
It's not the nicest solution, but it should work.

Morris line chart is not working properly

I created this simple line chart using morris.js. But it is not showing data properly. I don't know why?
Please check it at js fiddle.
Js fiddle: link
new Morris.Line({
element: 'multi-line-mp',
data: [
{
day: 'Jan 1',
sales: '0',
purchases: '1'
},
{
day: 'Jan 2',
sales: '14',
purchases: '3'
},
{
day: 'Jan 3',
sales: '45',
purchases: '0'
},
{
day: 'Jan 4',
sales: '47',
purchases: '32'
},
{
day: 'Jan 5',
sales: '90',
purchases: '10'
}
],
xkey: 'day',
ykeys: ['Sales', 'Purchases'],
labels: ['Sales', 'Purchases'],
resize: true
});
The date format of your xkey (day) is not good, this is rather a string than a real date.
You have 2 choices:
change the format of the xkey to be a real date (like 2021-01-01 instead of Jan 1)
set the option parseTime to false, so that it won't try to format the string to be a date
In case you change the format of xkey, you still can change the way the date is displayed thanks to the function dateFormat (see the documentation for this here: http://morrisjs.github.io/morris.js/lines.html)

How to get Highcharts XAxis to Display in 2 Minute Intervals

I am somewhat new to Highcharts and I am trying to pull off something that I am sure can be done but I cant figure it out.
I have posted my jsfiddle here: https://jsfiddle.net/dfeagin/1hn6c9ad/7/
Here is what the data looks like in my categories section for that axis:
categories: ['1/20/2020 9:22:02 PM', '1/20/2020 9:22:03 PM', '1/20/2020 9:22:04 PM', '1/20/2020 9:22:08 PM', '1/20/2020 9:22:09 PM', '1/20/2020 9:22:10 PM', '1/20/2020 9:22:12 PM', '1/20/2020 9:22:14 PM', '1/20/2020 9:22:15 PM', '1/20/2020 9:22:16 PM', '1/20/2020 9:22:18 PM', '1/20/2020 9:22:19 PM'.....]
On the XAxis, which represents minutes, there are a total of 46 minutes between the start to end time frame. I want to show two minute increments and just show the minute number vs. a date/time stamp:
0 2 4 6 8 10 ..... 42 44 46
How can I get it to do that? The data will have differing numbers of data points between those two minute increments but I want the 2 min intervals to be consistent.
Another note: I am generating the data that I feed to Highcharts in a .net web application so if it helps the situation I can send in a series of minute numbers vs. time/date stamps. So I could be sending over:
categories: ['0', '0', '0', '1', '1', '2', '2', '2', '2', '2', '2', '2', '3', ... '43', '43', '43', '44', '44', '45', '45', '45', '45', '45', '45', '45', '46', '46']
I think you would be better setting the chart up as spline rather than each series, with a datetime x-axis and putting data into the series as an array of date/value x/y pairs.
This way you can have more control over the xAxis ticks in this case setting tick interval to 2 minutes, and is more flexible in general.
Use a custom formatter to manipulate the tick value.
https://jsfiddle.net/gazx45oy/
Chart type:
chart: {
type: 'spline',
xAxis settings:
xAxis: [{
type: 'datetime',
startOnTick: true,
minPadding: 0,
tickInterval: 120000,
labels: {
formatter: function () {
return (this.value - this.axis.min) / 60000;
},
Series data:
var vesselSteamTemp = [
[Date.UTC(2020,20,1,9,22,2), 119],

24-hour dropdown menu using Array.from( Array(n) ).map(String)

trying to get better at making my code less dense but I'm stumped on this one. what's the best way to use a dropdown menu to choose between options 1-24, while the array is nested within an object?
I am trying to make a chrome extension to create notifications for different time functions from the local time (ie 1hr, 3hrs, 12hrs, etc)
I know it works with this array here:
var d = new Dropdown({
id: 'd',
val: 'custom:',
data: ['1 hour', '2 hours', '3 hours', '4 hours', '5 hours', '6 hours', '7 hours', '8 hours', '9 hours', '10 hours', '11 hours', '12 hours', '13 hours', '14 hours', '15 hours', '16 hours', '17 hours', '18 hours', '19 hours', '20 hours', '21 hours', '22 hours', '23 hours', '24 hours'],
cb: function cb(newval) {
alert(newval);
}
});
for the future, to avoid the rewriting of 24 separate options would this logic work? it returns the items as an array of strings with the values being updated as the first parameter, but I am not sure if it's bad practice.
let h = Array.from(Array(24).toString(),
(_hour, index) => `${[index + 2]} hours`).map(String);
const itr = h.values();
console.log(Array.isArray(h)); // outputs true
console.log(itr); // outputs {[Iterator]}
// here's where I get lost
if there's an easier way that I'm just missing please let me know. I prefer this to the html input, since I am not messing with dates in the timer, just logging the local time +n.
Use map and check to use plural or not.
const hours = new Array(24).fill(0).map((_, i) => `${i+1} hour${i > 0 ? 's' : ''}`)
console.log(hours)
You can use spread the array and then use map() on it.
const arr = [...Array(24)].map((_, i) => `${i + 1} hours`);
console.log(arr)

how to get date Object when select from dropdown list

I have a drop down list(screenshot attached),when we select any one like this year so how can we send StartIndex and EndIndex in backend using date Object using javascript,angular js.
Thanks In Advance any help will be appriciated
StatIndex:2016-01-01T00:00:00+5:30
EndIndex :2016-12-31T23:59:59+5:30
code for Index Range
this.indexRanges = ['This Year', 'Last Year', 'This Quarter', 'Last Quarter', 'This Month', 'Last Month', 'This Week',
'Last Week', 'Last 72 Hours', 'Last 48 Hours', 'Last 24 Hours', 'Today', 'Yesterday', 'Last Hours', 'This Hours',
'This 30 Minutes', 'Last 30 Minutes', 'This 15 Minutes', 'Last 15 Minutes', 'This 10 Minutes', 'Last 10 Minutes'];
send in backend using date Object using javascript,angular js
You most likey want the start date:
StatIndex:2016-01-01T00:00:00+5:30
This can be converted to a Date object quite easily using the Date constructor. For example:
var StatIndex = '2016-01-01T00:00:00+5:30';
const date = Date(StatIndex);
const toSend = {date:date};
const json = JSON.stringify(toSend);
As #Hassan Tariq mentioned in the comments, you need to write your own methods for it. To help you with there is a good library to play with dates moment.js

Categories

Resources