Formatar data

17 respostas
G

galera to precisando formatar data e não estou conseguindo

estou fazendo assim:

Date data = new Date(); SimpleDateFormat spf = new SimpleDateFormat("dd/MM/yyyy"); spf.format(listaLancamentos.get(i).getDataPeriodo());

onde listaLancamentos.get(i).getDataPeriodo() é a data que eu tenho que converter

17 Respostas

Fexx

E o que aparece? dá algum erro?

A

já deu um print pra saber o valor que o listaLancamentos.get(i).getDataPeriodo() está trazendo?

andrepapaz

Gabriel,

Você pode confirmar se tanto a classe Date do new quanto a que retorna do getDataPeriodo são da java.util?

G

cara o listaLancamentos.get(i).getDataPeriodo() tras a data no formato yyyy/mm/dd

G

date é do proprio java mesmo mas getDataPeriodo() é uma classe que criei que me retorna a data que o usuario setar

joaoorso

Esse :

getDataPeriodo()

retorna um Date ou uma String ?

andrepapaz

Fiquei na dúvida também se é uma string ou um date.

Mas gabriel, sei que é do java as datas, mas é do java.util ou do java.sql?

Confira no import da classe que você está da Classe Lancamento!

G

cara java util e o getdatePeriodo é string

andrepapaz
gabrielnsouza:
cara java util e o getdatePeriodo é string

String não vai, o método format recebe um java.util.Date

achei isso aqui, olha:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class Test1 {
	
	public static void main(String[] args) {

	      SimpleDateFormat formatter;
	      String output;

	      formatter = new SimpleDateFormat("MM/dd/yyyy");
	      Date d = null;
	      try {
			d = formatter.parse("12/20/08");//user entry date
		} catch (ParseException e) {
			e.printStackTrace();
		}
	      output = formatter.format(d.getTime());

	      System.out.println(output);
	   
	}

}

Entendeu?

:thumbup:

andrepapaz

No caso acho melhor você fazer a sua Classe Lancamento ter o campo como Date e mudar os getters e setters.

Afinal …um getDataPeriodo você espera um Date.

:thumbup:

G

o problema é que isso já não está tão pequeno e eu não mexo sozinho portanto se eu mudar vai dar erro em varios lugares onde está sendo usado
pq na verdade nem foi eu quem criou essa variavel desse jeito…

andrepapaz

Beleza então, então ali fora usa o .parse e é só correr para o abraço!

^^

G

pessoal criei a função

public String FormatarData(String Data, String Formato) {

        SimpleDateFormat sdf1 = new SimpleDateFormat(Formato);                    
        SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy");
               
        String ent = Data;
        Date val2;
        String saida = "";
        try {
            val2 = sdf1.parse(ent);
            saida = sdf2.format(val2); 
        } catch (ParseException ex) {
            Logger.getLogger(Library.class.getName()).log(Level.SEVERE, null, ex);
            //System.out.println(ex.printStackTrace());
        }
                
        return saida;
        
    }

onde data é a data passada no formato yyyy/mm/dd e o formato é o formato atual yyyy/mm/dd

- criei dois objetos SimpleDateFormat um para o formato que vem e outro para o que eu quero e os seto com os respectivos valores - na linha
val2 = sdf1.parse(ent);
o valor de ent é a data de hj em String mas no formato 2012/03/01 então dei um parse para transformar esse valor em data usando o sdf1 que é referente ao formato que vem, mas quando ele passa a data para val2 ela vai como 01/01/2012

queria saber se alguem pode me ajudar, porque que está passando a data para o primeiro dia do mês ele converte para o formato que eu quero mas a data fica a 1° do ano.

AJUDA ?!?!?!

andrepapaz

Gabriel,

Você não quer conferir se os imports estão corretos para java.util.Date e se os valores que você está passando para o método não estão corretos mesmo, porque eu coloquei seu método aqui no java, criei um test com o junit e funcionou, olha só como eu passei os parâmetros para função:

public class FormataDatasTest {

	@Test
	public void testaFormatarDatas() {
		FormataDatas formatar = new FormataDatas();
		
		String datastring = formatar.FormatarData("2012/03/01", "yyyy/MM/dd");
		
		assertTrue(datastring.equals("01/03/2012"));
		
	}

}

E o jUnit deu ok aqui.

Confirma aí!

:thumbup:

G

Cara vou dar uma olhada
vlw.

uaslei_Java
package AutoProgram;

import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author Uaslei
 */
public class OleDate {
    
    private Calendar calendar = Calendar.getInstance();

    public Calendar getCalendar() {
        return calendar;
    }

    public Date getDate() {
        return calendar.getTime();
    }

    public OleDate() {

    }

    public OleDate(int year, int month, int date) {
        calendar.set(year, month, date);
        //super(year, month, date);
    }

    public OleDate(int year, int month, int date, int hrs, int min, int sec) {
        calendar.set(year, month, date, hrs, min, sec);
        //super(year, month, date, hrs, min, sec);
    }

    public OleDate(long date) {
        calendar.setTimeInMillis(date);
        //super(date);
    }


    public OleDate(double date) {

        setDate(date);
    }
    // Source code copied from MFC 4.21 and modified
    // Half a second, expressed in days
    static double HALF_SECOND = (1.0 / 172800.0);

    public final void setDate(double dtSrc) {

        // source code copied from MFC 4.21 and modified

        long nDays; // Number of days since Dec. 30, 1899
        long nDaysAbsolute; // Number of days since 1/1/0
        long nSecsInDay; // Time in seconds since midnight
        long nMinutesInDay; // Minutes in day
        long n400Years; // Number of 400 year increments since 1/1/0
        long n400Century; // Century within 400 year block (0,1,2 or 3)
        long n4Years; // Number of 4 year increments since 1/1/0
        long n4Day; // Day within 4 year block
        // (0 is 1/1/yr1, 1460 is 12/31/yr4)
        long n4Yr; // Year within 4 year block (0,1,2 or 3)
        boolean bLeap4 = true; // TRUE if 4 year block includes leap year

        // values in terms of year month date.
        int tm_sec;
        int tm_min;
        int tm_hour;
        int tm_mday;
        int tm_mon;
        int tm_year;
        int tm_wday;
        int tm_yday;

        double dblDate = dtSrc; // temporary serial date

        // If a valid date, then this conversion should not overflow
        nDays = (long) dblDate;

        // Round to the second
        dblDate += ((dtSrc > 0.0) ? HALF_SECOND : -HALF_SECOND);

        // Add days from 1/1/0 to 12/30/1899
        nDaysAbsolute = (long) dblDate + 693959L;
        dblDate = Math.abs(dblDate);
        nSecsInDay = (long) ((dblDate - Math.floor(dblDate)) * 86400.);

        // Leap years every 4 yrs except centuries not multiples of 400.
        n400Years = (long) (nDaysAbsolute / 146097L);
        // Set nDaysAbsolute to day within 400-year block

        nDaysAbsolute %= 146097L;
        // -1 because first century has extra day
        n400Century = (long) ((nDaysAbsolute - 1) / 36524L);
        // Non-leap century

        if (n400Century != 0) {

            // Set nDaysAbsolute to day within centurY
            nDaysAbsolute = (nDaysAbsolute - 1) % 36524L;

            // +1 because 1st 4 year increment has 1460 days
            n4Years = (long) ((nDaysAbsolute + 1) / 1461L);

            if (n4Years != 0) {
                n4Day = (long) ((nDaysAbsolute + 1) % 1461L);
            } else {
                bLeap4 = false;
                n4Day = (long) nDaysAbsolute;
            }
        } else {
            // Leap century - not special case!
            n4Years = (long) (nDaysAbsolute / 1461L);
            n4Day = (long) (nDaysAbsolute % 1461L);
        }

        if (bLeap4) {
            // -1 because first year has 366 days
            n4Yr = (n4Day - 1) / 365;

            if (n4Yr != 0) {
                n4Day = (n4Day - 1) % 365;
            }
        } else {
            n4Yr = n4Day / 365;
            n4Day %= 365;
        }

        tm_year = (int) (n400Years * 400 + n400Century * 100 + n4Years * 4 + n4Yr);

        // Handle leap year: before, on, and after Feb. 29.
        if (n4Yr == 0 && bLeap4 && n4Day == 59) {
            /* Feb. 29 */
            tm_mon = 2;
            tm_mday = 29;
        } else {
            if (n4Yr == 0 && bLeap4 && n4Day >= 59) {
                --n4Day;
            }

            // Make n4DaY a 1-based day of non-leap year and compute

            // month/day for everything but Feb. 29.
            ++n4Day;

            // Month number always >= n/32, so save some loop time
            for (tm_mon = (int) ((n4Day % 5) + 1); n4Day > rgMonthDays[tm_mon]; tm_mon++) {
            }

            tm_mday = (int) (n4Day - rgMonthDays[tm_mon - 1]);
        }

        if (nSecsInDay == 0) {
            tm_hour = tm_min = tm_sec = 0;
        } else {
            tm_sec = (int) (nSecsInDay % 60L);
            nMinutesInDay = nSecsInDay / 60L;
            tm_min = (int) (nMinutesInDay % 60);
            tm_hour = (int) (nMinutesInDay / 60);
        }

        calendar.set(Calendar.YEAR, tm_year - 1900);
        calendar.set(Calendar.MONTH, tm_mon - 1);
        calendar.set(Calendar.DATE, tm_mday);
        calendar.set(Calendar.HOUR, tm_hour);
        calendar.set(Calendar.MINUTE, tm_min);
        calendar.set(Calendar.SECOND, tm_sec);

    }
    // source code copied from MFC 4.21 and modified
    static int rgMonthDays[] = {0, 31, 59, 90, 120, 151, 181, 212, 243,
        273, 304, 334, 365};

    public double toDouble() {
        // source code copied from MFC 4.21 and modified.

        int wYear = calendar.get(Calendar.YEAR) + 1900;
        int wMonth = calendar.get(Calendar.MONTH) + 1;
        int wDay = calendar.get(Calendar.DATE);
        int wHour = calendar.get(Calendar.HOUR);
        int wMinute = calendar.get(Calendar.MINUTE);
        int wSecond = calendar.get(Calendar.SECOND);

        // Check for leap year and set the number of days in the month
        boolean bLeapYear = ((wYear & 3) == 0)
                && ((wYear % 100) != 0 || (wYear % 400) == 0);

        int nDaysInMonth = rgMonthDays[wMonth] - rgMonthDays[wMonth - 1]
                + ((bLeapYear && wDay == 29 && wMonth == 2) ? 1 : 0);

        // Cache the date in days and time in fractional days
        long nDate;
        double dblTime;

        // It is a valid date; make Jan 1, 1AD be 1
        nDate = wYear * 365L + wYear / 4 - wYear / 100 + wYear / 400
                + rgMonthDays[wMonth - 1] + wDay;

        // If leap year and it's before March, subtract 1:
        if (wMonth >= 2 && bLeapYear) {
            --nDate;
        }

        // Offset so that 12/30/1899 is 0
        nDate -= 693959L;

        dblTime = (((long) wHour * 3600L) + // hrs in seconds
                ((long) wMinute * 60L) + // mins in seconds
                ((long) wSecond)) / 86400.;

        double dtDest = (double) nDate + ((nDate >= 0) ? dblTime : -dblTime);

        return dtDest;
    }

}

Depois vc pode passar esse codigo para conversão

GregorianCalendar gc = new GregorianCalendar();
        txtData.setText(Data.formatoDataSimples.format(gc.getTime()));
        txtData1.setText(Data.formatoDataSimples.format(gc.getTime()));

 datas = new java.sql.Date(Data.formatoDataSimples.parse(txtData.getText()).getTime());
uaslei_Java
GregorianCalendar gc = new GregorianCalendar();
        txtData.setText(Data.formatoDataSimples.format(gc.getTime()));
      
 datas = new java.sql.Date(Data.formatoDataSimples.parse(txtData.getText()).getTime());
Criado 29 de fevereiro de 2012
Ultima resposta 1 de mar. de 2012
Respostas 17
Participantes 6