Please help me with my code?

Discussion in 'Spigot Plugin Development' started by Daniel, May 21, 2016.

  1. Hello I'm trying to get someone first date they join my server so I have this code . But its only showing numbers not Month/Day/Year I'm not sure how to use SimpleDataFormat or DataTimeformatter
    Code (Text):
      player.sendMessage(ChatColor.translateAlternateColorCodes('&', "&6First Joined: &b" + player.getFirstPlayed() + ""));
     
  2. https://hub.spigotmc.org/javadocs/spigot/org/bukkit/OfflinePlayer.html#getFirstPlayed()

    You need to use a utility (or write one) to format that timestamp into day/month/year. There are plenty of tutorials, google it.
     

  3. Code (Text):
    GregorianCalendar gc = new GregorianCalendar();
    gc.setTimeInMillis(player.getFirstPlayed());
    int date     = gc.get(Calendar.DAY_OF_MONTH);
    int month = gc.get(Calendar.MONTH) + 1;
    int year     = gc.get(Calendar.YEAR);
     
  4. Even better:
    Code (Text):
    Date date = new Date(player.getFirstPlayed());
    player.sendMessage(date.toString());
     
    • Like Like x 1
  5. It gets the number of seconds since 1/1/1970.

    Use the division and modulo (%) operator to convert this to years, months, days. It is a very important and powerful mathematical operator, especially for dealing with time or repeating code/loops.

    Something like:
    Code (Java):

    long time = p.getFirstPlayed();
    int years = Math.floor(time / 1314000F); // 1314000 is one year in seconds, unless i screwed up the math.
    time = time % 1314000F ; // reduce time to the remainder that will not fit into a year-sized unit, convert this to months by the same method, then to days, ect..

    You end up with the time since 1970 in years, then months, then days... There are other ways, and probably even a function in the java 8 "time" libraries for conversion to a timestamp.

    Here is the API-spoonfed method.
    Code (Java):

    // according to stack exchange:
    new Timestamp(long seconds);

    // or:
    Date date = new Date(logEvent.timeSTamp);
    DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
    String dateFormatted = formatter.format(date);
     
     
    • Informative Informative x 1