In c# I use the below method in order to get the CultureInfo.
System.Globalization.CultureInfo.CurrentCulture.Name // output :en-US
Can any one tell me how can I get the CultureInfo in JavaScript?
Very easy way is to render it into the view, like this:
<script>
var cultureInfo = '#System.Globalization.CultureInfo.CurrentCulture.Name';
</script>
This is razor syntax, if you use classic asp.net, then use:
<script>
var cultureInfo = '<%= System.Globalization.CultureInfo.CurrentCulture.Name %>';
</script>
This is a very old post an is definately in need of an update. All major browsers now support the navigator property. Simply use
var lang = navigator.language
It depends on your goal. If you want the entire website to be treated as the same culture as your server, you can use System.Globalization.CultureInfo.CurrentCulture.Name only and remove the if-then shorthand within the first code snippet. This is not advisable if you have a global website.
Include the following in the bottom of your page:
<input id="currentCulture" type="hidden" value="<%=((Request.UserLanguages != null && Request.UserLanguages.Length > 0) ? new System.Globalization.CultureInfo(Request.UserLanguages.First(), true).Name : System.Globalization.CultureInfo.CurrentCulture.Name) %>" />
Now you can retrieve the culture info specific to the user, within your javascript, using:
$("#currentCulture").val(); //Jquery
document.getElementById("currentCulture").value; //Pure javascript
Within your code behind, any datetime parsing you require, pass in the culture info provider to the parse and tryparse and Convert.ToDateTime functions by using the below:
CultureInfo info = ((Request.UserLanguages != null && Request.UserLanguages.Length > 0) ? new CultureInfo(Request.UserLanguages.First(), true) : System.Globalization.CultureInfo.CurrentCulture);
Note: if you use Jquery UI and have cultures not included by default (such as en-CA or en-GB), you will have to add them. You can retrieve the code here:
https://code.google.com/p/dobo/source/browse/trunk/dobo/Kooboo.CMS/Kooboo.CMS.Web/Scripts/jquery-ui-i18n/?r=7
You can then include it dynamically by following the below example:
$.datepicker.regional['en-CA'] = { "Name": "en-CA", "closeText": "Close", "prevText": "Prev", "nextText": "Next", "currentText": "Today", "monthNames": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ""], "monthNamesShort": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ""], "dayNames": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], "dayNamesShort": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], "dayNamesMin": ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], "dateFormat": "dd/mm/yy", "firstDay": 0, "isRTL": false };
$(".datepick").datepicker($.datepicker.setDefaults($.datepicker.regional[$("#currentCulture").val()]));
Related
I am trying to create a unique object of years and months based on an array of dates, see what I mean below:
const availableDates = ["26-01-2022", "30-01-2022", "02-03-2022", "16-04-2022", "01-01-2023"]; // This list will be really long, just an example
I want to create a unique object like below using availableDates but having issues trying to figure it out:
const uniqueDates = {
"2022": ["Jan", "Mar", "Apr"],
"2023": ["Jan"]
};
If you have a better way that I achieve this, please let me know!
Thanks in advance
We can use Array.reduce to create the desired map, and using a Set to ensure we only keep a unique set of months for each year.
const availableDates = ["26-01-2022", "30-01-2022", "02-03-2022", "16-04-2022", "01-01-2023", "01-01-2023"];
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const uniqueDates = availableDates.reduce((acc, dt) => {
let [day, month, year] = dt.split("-");
acc[year] = [...new Set(acc[year] || []).add(months[month - 1])];
return acc;
}, {})
console.log("Unique object:", uniqueDates)
Maybe something like this:
let month = {
"01" : "Jan",
"02" : "Feb",
"03" : "Mar",
"04" : "Apr",
// ...
};
let res = ["26-01-2022", "30-01-2022", "02-03-2022", "16-04-2022", "01-01-2023"].reduce((acc, el) => {
let arr = el.split("-");
if( acc[arr[2]] && !acc[arr[2]].includes(month[arr[1]])){
acc[arr[2]].push(month[arr[1]])
} else if(!acc[el[2]]){
acc[arr[2]] = [month[arr[1]]]
}
return acc;
}, {})
console.log(res)
I want to display an Icon and use parameteres that API gives me back. Whenever I try to do it, I get undefined. Tryed to do this like this :
import React from 'react';
import './WeatherBox.css'
import { Icons } from '../../icons';
const dateBuilder = (d) => {
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
let day = days[d.getDay()];
let date = d.getDate();
let month = months[d.getMonth()];
let year = d.getFullYear();
return `${day} ${date} ${month} ${year}`
}
const WeatherBox = ({result}) => {
return (
<div className="locationDate">
<span>{result.location}</span>
<span>{dateBuilder(new Date())}</span>
<span>{result.temp}°C</span>
{/* <span>{Icons.Clouds}</span> */}
<span>{result ? Icons.result.sky : null}</span>
</div>
)
}
export default WeatherBox;
result.sky is variable that API gives me back, something like "Clouds" "Sunny" etc. that's how my icons are named and i want to display them when API is loaded. Condition I used doesn't work, and It wants to display before API is even returned.
The answer is I tried to refer to Icons wrong. Instead of using Icons.result.sky, i had to do It like Icons[result.sky].
Just wondering, I have the following setup:
new Vue({
el: '#app',
const: {
monthNames : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
},
data: {
year : (new Date()).getFullYear(),
month : (new Date()).getMonth(),
monthName : this.monthNames[(new Date()).getMonth()],
day : (new Date()).getDate(),
},
...
)}
As you can see, I'm trying to pass in (new Date()).getMonth() into the monthNames array from const - but console is returning the Uncaught TypeError: Cannot read property '4' of undefined.
So my question is simply: how do I reference monthNames from within data?
N.B. I'm using the most recent js dev build.
You could declare it outside the Vue instance or perhaps in another module and import it before using like import { monthNames } from './constants', and then use it whenever you want.
If you want to keep it inside that particular Vue instance then i think it would be better to put it inside the computed structure for caching.
Example:
const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
new Vue({
el: '#app',
data: {
year : (new Date()).getFullYear(),
month : (new Date()).getMonth(),
monthName : monthNames[(new Date()).getMonth()],
day : (new Date()).getDate(),
},
...
)
A question that matches yours: https://stackoverflow.com/a/46883212/7395911
A discussion about a constant structure within Vue: https://github.com/vuejs/vue/issues/6004
I'm a newbie to Vue but you can attach it to the Vue simply by calling:
Vue.prototype.$monthNames
And then calling it within data using monthNames
From what I can find you can also use mixins (seems a bit dangerous, affects all components) or simply just declaring a constant before loading the Vue instance.
Am using the following code to display MySQL data in a Morris Chart. All works good EXCEPT if I have TWO or more records on the same day, only shows as ONE in the Morris Chart.
PHP File
$mysqli = mysqli_connect($hostname_membership, $username_membership, $password_membership, $database_membership);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT id FROM details WHERE MemberStatus = 'Active' AND PaymentStatus NOT REGEXP 'Not'";
$result = mysqli_query($mysqli,$query);
$total_rows = $result->num_rows;
$array = array();
foreach($mysqli->query('SELECT DateAdded, COUNT(*) FROM details GROUP BY DateAdded') as $row) {
$year = date("Y-m-d",strtotime($row['DateAdded']));
array_push($array,array('Year'=>$year, 'Numb'=>$row['COUNT(*)'],'Total'=>$total_rows));
}
echo json_encode($array);
$mysqli->close();
Morris JS
$.getJSON("js/morris.php", function (json) {
Morris.Area({
element: 'morris-area-chart',
data: json,
xkey: 'Year',
xLabelFormat: function (x) {
var IndexToMonth = [ "Jan", "Feb", "Mar", "Apr", "Mar", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var month = IndexToMonth[ x.getMonth() ];
var year = x.getFullYear();
return month + ' ' + year;
},
xLabels: 'month',
ykeys: ['Numb','Total'],
labels: ['Signups / Renewals','Total Active Members'],
pointSize: 2,
hideHover: 'auto',
resize: true,
dateFormat: function (x) {
var d = new Date(x);
var MyDateString;
d.setDate(d.getDate());
var monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
return ("0" + d.getDate()).slice(-2) +' '+monthNames[d.getMonth()]+' '+d.getFullYear();
}
});
return false;
});
And my JSON Output is
[{"Year":"2016-10-27","Numb":"1","Total":11},{"Year":"2016-10-28","Numb":"1","Total":11},{"Year":"2016-10-31","Numb":"1","Total":11},{"Year":"2016-11-02","Numb":"1","Total":11},{"Year":"2016-11-05","Numb":"1","Total":11},{"Year":"2016-11-07","Numb":"1","Total":11},{"Year":"2016-11-08","Numb":"1","Total":11},{"Year":"2016-11-09","Numb":"1","Total":11},{"Year":"2016-11-10","Numb":"1","Total":11},{"Year":"2016-11-10","Numb":"1","Total":11},{"Year":"2016-11-16","Numb":"1","Total":11}]
As you can see from above, the JSON output has two identical records
{"Year":"2016-11-10","Numb":"1","Total":11},{"Year":"2016-11-10","Numb":"1","Total":11}
This is what shows as only ONE record on the Morris Chart. In this case, it's only one person signed up on the 10th Nov 16, when in fact it was TWO...
FYI ONLY - TOTAL is just that - TOTAL number of Signups. Whilst I like to have this as a running total, I can't work that out either. So am not to worried about it, not unless there is a simple solution.
What am I missing?
Have come up with a solution - seems to work - so far....
Replaced
SELECT DateAdded, COUNT(*) FROM details GROUP BY DateAdded
with
SELECT DateAdded, COUNT(*) FROM details GROUP BY DATE_FORMAT(DateAdded,"%Y-%m-%d")
Now just working on a running total...
I am formatting dates using moment.js with arabic locale (ar_SA) set.
moment.locale('ar_SA');
moment([2016,05,01]).format('MMM YYYY');
//output مايو ٢٠١٦
I would like to format only the month part using the locale, but the year in english, example: "مايو 2016" (the same as when formatting using the angular filter: | date:'MMM yyyy')
Is there a way to configure moment.js to do this automatically? (instead of splitting the month and year formatting and simply concatenating 2016 to .format('MMM'))
moment.updateLocale('en', {
months : [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
]
});
Source: https://momentjs.com/docs/#/customization/month-names/
I never did find a solution to this. I opted for a split/manual approach instead:
currentDate.format('MMM') + ' ' + currentDate.clone().locale('en').format('YYYY');