hustcc / timeago.js

:clock8: :hourglass: timeago.js is a tiny(2.0 kb) library used to format date with `*** time ago` statement.
https://timeago.org
MIT License
5.32k stars 410 forks source link

Use another number symbols #176

Closed sky93 closed 5 years ago

sky93 commented 5 years ago

Hello,

In standard persian language we don't use regular numbers like 1, 2, 3, 4, 5, 6, 7, 8, 9 and 0. Instead we have ۱, ۲, ۳, ۴, ۵, ۶, ۷, ۸, ۹ and ۰. In language file we only have %s. I need to replace 1 to ۱, 2 to ۲ and so on.

How can I do this in fa language file?

Thank you very much for your amazing library.

lolobosse commented 5 years ago

Hey

It was actually a cool exercise 😄 🎉

Here is the answer with room for improvement.

https://jsfiddle.net/3c1e087n/1/

(For those who do want to open an extra tab)


    var instance = timeago()
  const chars = ['۰','۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']

  const writePersian = (_number) => {
    const persian = []
    sNumber = _number.toString();

    for (var i = 0, len = sNumber.length; i < len; i += 1) {
        persian.push(+sNumber.charAt(i));
    }
    return persian.map((index)=> chars[index]).join('')
  }
const localeFunc = (number, index, total_sec) => {
  // number: the timeago / timein number;
  // index: the index of array below;
  // total_sec: total seconds between date to be formatted and today's date;
  return [
     ['just now', 'right now'],
    [writePersian(number) + ' seconds ago', 'in '+writePersian(number) + ' seconds'],
    ['1 minute ago', 'in 1 minute'],
    [writePersian(number) + ' minutes ago', 'in '+writePersian(number) + ' minutes'],
    ['1 hour ago', 'in 1 hour'],
    [writePersian(number) + ' hours ago', 'in '+writePersian(number) + ' hours'],
    ['1 day ago', 'in 1 day'],
    [writePersian(number) + ' days ago', 'in '+writePersian(number) + ' days'],
    ['1 week ago', 'in 1 week'],
    [writePersian(number) + ' weeks ago', 'in '+writePersian(number) + ' weeks'],
    ['1 month ago', 'in 1 month'],
    [writePersian(number) + ' months ago', 'in '+writePersian(number) + ' months'],
    ['1 year ago', 'in 1 year'],
    [writePersian(number) + ' years ago', 'in '+writePersian(number) + ' years']
  ][index];
};
// register your locale with timeago
timeago.register('my-locale', localeFunc);
console.log(instance)
// use it
document.write(instance.format('0216-06-12', 'my-locale'), instance.format('0216-06-12', 'en'));
sky93 commented 5 years ago

Thank you so much for your answer. I almost did the same thing. See my pull request.