الفريق العربي للبرمجةأرشيف المنتديات · 2000 – 2023
نسخة أرشيفية للقراءة فقط — التسجيل والمشاركة مغلقان، والمحتوى محفوظ كما كان.

تجربتي مع DateFormat

بدأه .S.T.A.L.K.E.R في 17 أغسطس 2011 · 26 رد · 1,208 مشاهدة · في JavaSE
مشاركة: واتساب X فيسبوك تيليجرام
#1 صاحب الموضوع

السلام عليكم

احتجت لطريقة لطباعة الوقت المراد بطريقة واضحة

مثلا "Before 3 Minutes" او "Today 11:15 am"

وبذلك خرج معي هذا الصف، ارجو ان يفيدكم:

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

/**
 *
 * @author MErsan
 */
public class DateFormatter {

    public static String formatDate(long time) {
        StringBuilder result = new StringBuilder();

        // 1- Check the year
        // 2- Check the Month
        // 3- Check the Day
        // 4- Check the Hours

        Date myDate = new Date(time);
        Date todayDate = new Date(System.currentTimeMillis());

        if (todayDate.getYear() - myDate.getYear() != 0) {
            // Not same year, and should append the whole time
            return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
        }
        // Same Year
        // now Check the month
        if (todayDate.getMonth() - myDate.getMonth() != 0) {
            return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
            // 16,
            // 11:55
            // PM
        }

        // Now Same Month
        // Check the day
        int daysDiff = todayDate.getDate() - myDate.getDate();
        if (daysDiff == 1) {// Yesterday
            result.append("Yesterday").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (daysDiff != 0) {
            return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);// Aug
            // 16,
            // 11:55
            // PM
        }

        // Same Day :')
        // Check the hour
        int hoursDiff = todayDate.getHours() - myDate.getHours();
        if (hoursDiff < 0) {// Invalid Time
            // :@
            result.append("Today").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
            result.append("Today").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (hoursDiff != 0) {// Hours Diff less than 3 hours, but not
            // current hour
            int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();

            result.append("Before").append(' ');
            result.append(hoursDiff).append(' ');
            result.append("Hours").append(' ');
            result.append("and").append(' ');
            result.append(Math.abs(mintuesDiff)).append(' ');
            result.append("Minutes");
            System.err.println("Case 6");
            return result.toString();
        } else if (hoursDiff == 0) {// Same Hours
            int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
            if (mintuesDiff < 1) {// Seconds Only {Same Minute}
                int secondsDiff = todayDate.getSeconds() - myDate.getSeconds();
                result.append("Before").append(' ');
                result.append(Math.abs(secondsDiff)).append(' ');
                result.append("Seconds");
                return result.toString();
            } else {
                result.append("Before").append(' ');
                result.append(Math.abs(mintuesDiff)).append(' ');
                result.append("Minutes");
                return result.toString();
            }
        }

        // Default
        return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
    }
}

لا مانع من اي تعليق لل Optimization

تم تعديل هذه المشاركة بواسطة .S.T.A.L.K.E.R في 17 أغسطس 2011 في 03:15

1
#2

تسلم يا ابوعرسان فعلا جميله

بس عندى حته صغيره كدا وانا بقرا الكود

ايه الفرق بين الشرطين

if (hoursDiff < 0) {// Invalid Time
        	// :@
        	result.append("Today").append(' ');
        	result.append(new SimpleDateFormat("hh:mm a").format(myDate));
        	return result.toString();
    	} else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
        	result.append("Today").append(' ');
        	result.append(new SimpleDateFormat("hh:mm a").format(myDate));
        	return result.toString();

جارى تكمله الكود والمحاوله لايجاد ثغرات ROFL.gif

Software Developer
Mahmoudkelany.com


 

#3

ليه مش حسبت الساعات فى طريقه العرض هذه

result.append("Before").append(' ');
        	result.append("Hours").append(' ');
        	result.append("and").append(' ');
        	result.append(mintuesDiff).append(' ');
        	result.append("Minutes");

بتقوله انه قبل ساعات وكام دقيقه لكن ما تقوله قبل 10 ساعات و30 دقيقه مثلا يعنى

Software Developer
Mahmoudkelany.com


 

#4
Mahmoud Kelany كتب:

تسلم يا ابوعرسان فعلا جميله

بس عندى حته صغيره كدا وانا بقرا الكود

ايه الفرق بين الشرطين

if (hoursDiff < 0) {// Invalid Time
        	// :@
        	result.append("Today").append(' ');
        	result.append(new SimpleDateFormat("hh:mm a").format(myDate));
        	return result.toString();
    	} else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
        	result.append("Today").append(' ');
        	result.append(new SimpleDateFormat("hh:mm a").format(myDate));
        	return result.toString();

جارى تكمله الكود والمحاوله لايجاد ثغرات ROFL.gif

في الشرط الاول:

اذا كان الوقت المطلوب اكبر من الوقت الحالي: (في الكود اللي اعمل به ذلك خطأ ) لذلك كتبت Invalid Time

في الشرط الثاني :

اذا كان الفرق بين الوقت الحالي و الوقت المطلوب اكبر من 3 ساعات (اعتبرها ان الوقت يجب ان يكتب كله ) و ليس بصيغة Before

اي اعتبره بعيد بعض الشيء عن الوقت الحالي

Mahmoud Kelany كتب:

ليه مش حسبت الساعات فى طريقه العرض هذه

result.append("Before").append(' ');
        	result.append("Hours").append(' ');
        	result.append("and").append(' ');
        	result.append(mintuesDiff).append(' ');
        	result.append("Minutes");

بتقوله انه قبل ساعات وكام دقيقه لكن ما تقوله قبل 10 ساعات و30 دقيقه مثلا يعنى

لماذا اقول له الساعات، اذا كانت المدة خلال الساعة الحالية؟

اعتقد انه قبل 15 دقيقة تكون كافية

خطأ مطبعي :lol:

تم تعديل هذه المشاركة بواسطة .S.T.A.L.K.E.R في 17 أغسطس 2011 في 02:10

#5
.S.T.A.L.K.E.R كتب:

في الشرط الاول:

اذا كان الوقت المطلوب اكبر من الوقت الحالي: (في الكود اللي اعمل به ذلك خطأ ) لذلك كتبت Invalid Time

في الشرط الثاني :

اذا كان الفرق بين الوقت الحالي و الوقت المطلوب اكبر من 3 ساعات (اعتبرها ان الوقت يجب ان يكتب كله ) و ليس بصيغة Before

اي اعتبره بعيد بعض الشيء عن الوقت الحالي

تمام بس الشرط الاول والثانى هو نفس الكود اللى بينفذه

.S.T.A.L.K.E.R كتب:

لماذا اقول له الساعات، اذا كانت المدة خلال الساعة الحالية؟

اعتقد انه قبل 15 دقيقة تكون كافية

خطأ مطبعي :lol:

تمام :) ولايهمك

بحاول ابسط الكود شويه :)

Software Developer
Mahmoudkelany.com


 

#6
Mahmoud Kelany كتب:

تمام بس الشرط الاول والثانى هو نفس الكود اللى بينفذه

حاليا صحيح

لكن ان اردت التحديث عليه، لن اضطر للكثير

#7

جرب الكود دا كدا

public static void main(String[] args) {
    	long timeInLong = 1313533861880L;  
    	System.out.println(new SimpleDateFormat("hh:mm a").format(new Date(timeInLong)));
    	System.out.println(formatDate(timeInLong));
	}

النتيجه كانت الاتى

اقتباس
12:31 AM

Before 1 Hours and -8 Minutes

.S.T.A.L.K.E.R كتب:

حاليا صحيح

لكن ان اردت التحديث عليه، لن اضطر للكثير

if (hoursDiff < 0) {// Invalid Time
            // :@
            result.append("Today").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        } else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
            result.append("Today").append(' ');
            result.append(new SimpleDateFormat("hh:mm a").format(myDate));
            return result.toString();
        }

ما هو نفس الكود اهووو

نفس الكود بين الشرطين

Software Developer
Mahmoudkelany.com


 

#8
Mahmoud Kelany كتب:

جرب الكود دا كدا

public static void main(String[] args) {
    	long timeInLong = 1313533861880L;  
    	System.out.println(new SimpleDateFormat("hh:mm a").format(new Date(timeInLong)));
    	System.out.println(formatDate(timeInLong));
	}

عندي النتيجة

01:31 AM
Before 1 Hours and 4 Minutes

اقتباس

ما هو نفس الكود اهووو

نفس الكود بين الشرطين

اعرف انه نفس النتيجة، و كما اخبرتك (عندما اريد التحديث عليه، اعرف اين احدّث) و لا اريد صنع if جديدة

#9
.S.T.A.L.K.E.R كتب:

عندي النتيجة

01:31 AM
Before 1 Hours and 4 Minutes

امال انا عندى بالسالب ليه

دلوقتى ظهرت نتيجه اخرى طبعا بس بالموجب :(

اعرف انه نفس النتيجة، و كما اخبرتك (عندما اريد التحديث عليه، اعرف اين احدّث) و لا اريد صنع if جديدة

اممم تمام فهمت قصدك بس اتركها فارغه :)

Software Developer
Mahmoudkelany.com


 

#10
اقتباس
اممم تمام فهمت قصدك بس اتركها فارغه

اتركها فارغة!!

يبدو انني لم استوعبك جيدا، هل من الممكن ان توضح لي الإشكال؟ مثال ان امكن على هذه ال if

شكرا

#11
.S.T.A.L.K.E.R كتب:

اتركها فارغة!!

يبدو انني لم استوعبك جيدا، هل من الممكن ان توضح لي الإشكال؟ مثال ان امكن على هذه ال if

شكرا

if (hoursDiff < 0) {// Invalid Time
        	return "Invalid Time";
    	} else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
        	result.append("Today").append(' ');
        	result.append(new SimpleDateFormat("hh:mm a").format(myDate));
        	return result.toString();
    	}

Software Developer
Mahmoudkelany.com


 

#12
Mahmoud Kelany كتب:

if (hoursDiff < 0) {// Invalid Time
        	return "Invalid Time";
    	} else if (hoursDiff > 3) {// Not Same Hour, Hour Diff more than 3 hours
        	result.append("Today").append(' ');
        	result.append(new SimpleDateFormat("hh:mm a").format(myDate));
        	return result.toString();
    	}

:blink: :blink: :blink: :blink: :blink: :blink: :blink: :blink: :blink: :mellow: :blink: :blink: :mellow:

#13

ايه علامات الاستغراب دى كلها :)

وضح ROFL.gifROFL.gifROFL.gifROFL.gif افصح

Software Developer
Mahmoudkelany.com


 

#14

بالنسبة لموضوع الدقائق بالسالب، يبدو ان كلامك سليم

و تم التعديل

شكرا

#15

حاولت تقليص الكود

لا اعلم الفرق بين العبء الخاص بالـ String.formate و الـ StringBuffer ايهما اسرع

فقد تكون غير مجديه لكن هذه محاوله :)

وقد استخدمت الـ String.formate فى عمل تشكيل للوقت لكن كان شكلها غير مريح

فاستبدلتها مره اخرى كان شكلها كالتالى

return String.format("Yesterday %tl:%tM %tp", myDate, myDate, myDate);

عالعموم هذا هو الكود

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

/**
 *
 * @author MErsan
 */
public class DateFormatter {

	public static String formatDate(long time) {
    	// 1- Check the year
    	// 2- Check the Month
    	// 3- Check the Day
    	// 4- Check the Hours
    	// 5- Check the Minutes
    	// 6- Check the Seconds

    	Date myDate = new Date(time);
    	Date todayDate = new Date(System.currentTimeMillis());

    	if (todayDate.getYear() - myDate.getYear() != 0) {
        	// Not same year, and should append the whole time
        	return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
    	}
    	// Same Year
    	// now Check the month
    	if (todayDate.getMonth() - myDate.getMonth() != 0) {
        	return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);
    	}
    	// Now Same Month
    	// Check the day
    	int daysDiff = todayDate.getDate() - myDate.getDate();
    	if (daysDiff == 1) {
        	// Yesterday
        	return String.format("Yesterday %s",
                	new SimpleDateFormat("hh:mm a").format(myDate));
    	} else if (daysDiff != 0) {
        	return new SimpleDateFormat("MMM dd, hh:mm a").format(myDate);
    	}
    	// Same Day :')
    	// Check the hour
    	int hoursDiff = todayDate.getHours() - myDate.getHours();
    	if (hoursDiff < 0) {
        	// Invalid Time
        	// :@
        	return String.format("Today %s",
                	new SimpleDateFormat("hh:mm a").format(myDate));
    	} else if (hoursDiff > 3) {
        	// Not Same Hour, Hour Diff more than 3 hours
        	return String.format("Today %s",
                	new SimpleDateFormat("hh:mm a").format(myDate));
    	} else if (hoursDiff != 0) {
        	// Hours Diff less than 3 hours, but not
        	// current hour
        	int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
        	return String.format("Before %d hour(s)",
                	hoursDiff) + (Math.abs(mintuesDiff) != 0
                	? String.format(" and %d minute(s)", Math.abs(mintuesDiff)) : "");
    	} else if (hoursDiff == 0) {
        	// Same Hours
        	int mintuesDiff = todayDate.getMinutes() - myDate.getMinutes();
        	if (mintuesDiff < 1) {
            	// Seconds Only {Same Minute}
            	int secondsDiff = todayDate.getSeconds() - myDate.getSeconds();
            	return String.format("Before %d second(s)", Math.abs(secondsDiff));
        	} else {
            	return String.format("Before %d minute(s)", Math.abs(mintuesDiff));
        	}
    	}
    	// Default
    	return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
	}

	public static void main(String[] args) {
    	long timeInLong = 1313539871880L;  // before 2 hours
    	System.out.println(formatDate(timeInLong));
	}
}

Software Developer
Mahmoudkelany.com


 

#16

هنا محاولتي:

import java.util.Date;
public class DateFormatter
{ 
    public static String formatDate(long time)
    {
        StringBuilder result = new StringBuilder(".");
        Date myDate = new Date(time);
        Date todayDate = new Date(System.currentTimeMillis());

        long totalSeconds = Math.abs(todayDate.getTime() - myDate.getTime()) / 1000;
        int years = (int) (totalSeconds / (60 * 60 * 24 * 30 * 12));
        totalSeconds -= (years * 60 * 60 * 24 * 30 * 12);
        int months = (int) (totalSeconds / (60 * 60 * 24 * 30));
        totalSeconds -= (months * 60 * 60 * 24 * 30);
        int days = (int) (totalSeconds / (60 * 60 * 24));
        totalSeconds -= (days * 60 * 60 * 24);
        int hours = (int) (totalSeconds / (60 * 60));
        totalSeconds -= (hours * 60 * 60);
        int minutes = (int) (totalSeconds / 60);
        int seconds = (int) (totalSeconds - (minutes * 60));

        String sep = "", nextSep = " and ";
        if(seconds > 0)
        {
            if(seconds > 1) result.insert(0, " seconds").insert(0, seconds);
            else result.insert(0, " second").insert(0, seconds);
            sep = nextSep;
            nextSep = ", ";
        }
        if(minutes > 0)
        {
            if(minutes > 1) result.insert(0, sep).insert(0, " minutes").insert(0, minutes);
            else result.insert(0, sep).insert(0, " minute").insert(0, minutes);
            sep = nextSep;
            nextSep = ", ";
        }
        if(hours > 0)
        {
            if(hours > 1) result.insert(0, sep).insert(0, " hours").insert(0, hours);
            else result.insert(0, sep).insert(0, " hour").insert(0, hours);
            sep = nextSep;
            nextSep = ", ";
        }
        if(days > 0)
        {
            if(days > 1) result.insert(0, sep).insert(0, " days").insert(0, days);
            else result.insert(0, sep).insert(0, " day").insert(0, days);
            sep = nextSep;
            nextSep = ", ";
        }
        if(months > 0)
        {
            if(months > 1) result.insert(0, sep).insert(0, " months").insert(0, months);
            else result.insert(0, sep).insert(0, " month").insert(0, months);
            sep = nextSep;
            nextSep = ", ";
        }
        if(years > 0)
        {
            if(years > 1) result.insert(0, sep).insert(0, " years").insert(0, years);
            else result.insert(0, sep).insert(0, " year").insert(0, years);
            sep = nextSep;
            nextSep = ", ";
        }

        if(todayDate.getTime() - myDate.getTime() > 0) result.insert(0, "Before ");
        else if(todayDate.getTime() - myDate.getTime() < 0) result.insert(0, "After ");
        else /*if(todayDate.getSeconds() == myDate.getSeconds())*/ return "Now!";
        return result.toString();
    } 
}
597657.png
#17

جرّبت كودك

و النتيجة كالتالي:

        long currentTime = System.currentTimeMillis();
        long startTime = System.currentTimeMillis();
        long h=1000;

        for (long i = currentTime; i < (currentTime + h); i++) {
            DateFormatter.formatDate(i);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("Diff1:" + (endTime - startTime));

        startTime = System.currentTimeMillis();
        for (long i = currentTime; i < (currentTime + h); i++) {
            DateFormatter2.formatDate(i);//Kelany
        }
        endTime = System.currentTimeMillis();
        System.out.println("Diff2:" + (endTime - startTime));

حيث Diff 1 هي نتيجتي

, Diff2 نتيجتك

و النتيجة كالتالي:

Diff1:23
Diff2:31
#18
Eng.Fouad كتب:

هنا محاولتي:

العمليه هذه كلها

long totalSeconds = Math.abs(todayDate.getTime() - myDate.getTime()) / 1000;
    	int years = (int) (totalSeconds / (60 * 60 * 24 * 30 * 12));
    	totalSeconds -= (years * 60 * 60 * 24 * 30 * 12);
    	int months = (int) (totalSeconds / (60 * 60 * 24 * 30));
    	totalSeconds -= (months * 60 * 60 * 24 * 30);
    	int days = (int) (totalSeconds / (60 * 60 * 24));
    	totalSeconds -= (days * 60 * 60 * 24);
    	int hours = (int) (totalSeconds / (60 * 60));
    	totalSeconds -= (hours * 60 * 60);
    	int minutes = (int) (totalSeconds / 60);
    	int seconds = (int) (totalSeconds - (minutes * 60));

تحسبها كدا

int s = myDate.getSeconds();
    	int m = myDate.getMinutes();
    	int h = myDate.getHours();

ليه تتعب نفسك ف حسابها وتحويل الميلى ثانيه الى ساعات ودقائق وثوانى متبقيه

بس تقريبا الفكره الخاصه بالموضوع لم تصلك بعد

هل ترى مثلا ان شاهدت تاريخ المشاركات الخاصه بالفيس بوك

ستجد 4 minutes ago

ومره تلاقيها

7 hours ago

ومره اخرى

18 seconds ago

ومره اخرى تلاقيها

August 13 at 2:55pm

هذه هى الفكره

Software Developer
Mahmoudkelany.com


 

#19
.S.T.A.L.K.E.R كتب:

جرّبت كودك

و النتيجة كالتالي:

حيث Diff 1 هي نتيجتي

, Diff2 نتيجتك

و النتيجة كالتالي:

Diff1:23
Diff2:31

تقصد النتيجه فالسرعه ؟؟؟

لالالا انا جربتها طلعت العكس

وكمان حاول تجربها اكثر من مره ستجد ان مره هذا اسرع ومره اخرى هذا اسرع وهكذا

Software Developer
Mahmoudkelany.com


 

#20

حتى عملت Random فى عمليه تشغيل كود مين الاول وكل مره بيطلع كودى اقل فى الوقت من الكود حقك

Software Developer
Mahmoudkelany.com


 

#21

قمت بتحويل من دوال الDate الى الCalendar حيث أن الأولى أغلب دوالها Deprecated :

import java.text.DateFormat;
import java.text.SimpleDateFormat;

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

/**
 *
 * @author MErsan
 */
public class DateFormatter {

	public static void main(String[] args) {
		long time = 1313539871880L;
		Date date = new Date(time);

		System.out.println( formatDate(time) );
		System.out.println( formatDate(date) );

	}

	public static String formatDate(long time) {
		return formatDate(new Date(time) );
	}

	public static String formatDate(Date otherDate) {
		StringBuilder result = new StringBuilder();

		GregorianCalendar now = new GregorianCalendar();
		GregorianCalendar other = new GregorianCalendar();
		other.setTime(otherDate);

		//  not the same year
		if ( now.get(Calendar.YEAR) != other.get(Calendar.YEAR) ) {
			return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(other.getTime());
		}

		// not the same month
		if ( now.get(Calendar.MONTH) != other.get(Calendar.MONTH) ) {
			return new SimpleDateFormat("MMM dd, hh:mm a").format(other.getTime());
		}

		if ( now.after(other) || now.equals(other)) { // in the same year and the same month

			// compute the differnece using manual way
			long diff = now.getTime().getTime() - other.getTime().getTime(); 

			long diffSeconds = diff / 1000;
			long diffMinutes = diff / (60 * 1000);
			long diffHours = diff / (60 * 60 * 1000);
			long diffDays = diff / (24 * 60 * 60 * 1000);

			// or using calendar api
			//long diffDays = now.get(Calendar.DAY_OF_MONTH) - other.get(Calendar.DAY_OF_MONTH) ;
			// etc...

			if ( diffDays == 1 ) { // Yesterday
				result.append("Yesterday");
				result.append(new SimpleDateFormat("hh:mm a").format(other.getTime()));
				return result.toString();
			}
			else if ( diffDays != 0 ) { // not the same day
				return new SimpleDateFormat("MMM dd, hh:mm a").format(other.getTime());
			}

			if ( diffHours > 3 ) { // same day, hours more than 3
				result.append("Today").append(' ');
				result.append(new SimpleDateFormat("hh:mm a").format(other.getTime()));
				return result.toString();
			}
			else if ( diffHours != 0 ) { // same day, hour less than 3
				result.append("Before").append(' ');
				result.append(diffHours).append(' ');
				result.append("Hours").append(' ');
				result.append("and").append(' ');
				result.append(Math.abs(diffMinutes)).append(' ');
				result.append("Minutes");
			}
			else {	// same day, same hour
				if ( diffMinutes  == 0 ) { // same mintue
					result.append("Before").append(' ');
					result.append(Math.abs(diffSeconds)).append(' ');
					result.append("Seconds");
					return result.toString();
				}
				else { // not the same mintues
					result.append("Before").append(' ');
					result.append(Math.abs(diffMinutes)).append(' ');
					result.append("Minutes");
					return result.toString();
				}
			}
		}

		return result.toString();
	}

}

http://informatic-ar.com منصة تعليمية عربية في علوم الحاسب والبرمجة

https://moalfat.com  للكتب الالكترونية والكورسات التعليمية

Everything we see now is just an engineering solution based on old science

#22

لدى سوال اخ وجدى

ليه استخدمت هذه الطريقه فى حساب الثوانى والدقائق والساعات

long diff = now.getTime().getTime() - other.getTime().getTime(); 

                        long diffSeconds = diff / 1000;
                        long diffMinutes = diff / (60 * 1000);
                        long diffHours = diff / (60 * 60 * 1000);
                        long diffDays = diff / (24 * 60 * 60 * 1000);

انا فعلا كنت عاوز اعدلها علشان الـ Deprecated Methods

وعدلتها لكن بطريقه تانيه وهى استخدام

Calendar.HOUR_OF_DAY
Calendar.MINUTE
Calendar.SECOND

وهذا هو التعديل

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 *
 * @author MErsan
 */
public class DateFormatter {

	public static String formatDate(long time) {
    	return formatDate(new Date(time));
	}

	public static String formatDate(Date time) {
    	// 1- Check the year
    	// 2- Check the Month
    	// 3- Check the Day
    	// 4- Check the Hours
    	// 5- Check the Minutes
    	// 6- Check the Seconds

    	GregorianCalendar myDate = new GregorianCalendar();
    	GregorianCalendar todayDate = new GregorianCalendar();
    	myDate.setTime(time);
    	if (todayDate.get(Calendar.YEAR) - myDate.get(Calendar.YEAR) != 0) {
        	// Not same year, and should append the whole time
        	return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
    	}
    	// Same Year
    	// now Check the month
    	if (todayDate.get(Calendar.MONTH) - myDate.get(Calendar.MONTH) != 0) {
        	return new SimpleDateFormat("MMM dd, hh:mm a").format(time);
    	}
    	// Now Same Month
    	// Check the day
    	int daysDiff = todayDate.get(Calendar.DAY_OF_MONTH) - myDate.get(Calendar.DAY_OF_MONTH);
    	if (daysDiff == 1) {
        	// Yesterday
        	return String.format("Yesterday %s",
                	new SimpleDateFormat("hh:mm a").format(time));
    	} else if (daysDiff != 0) {
        	return new SimpleDateFormat("MMM dd, hh:mm a").format(time);
    	}
    	// Same Day :')
    	// Check the hour
    	int hoursDiff = todayDate.get(Calendar.HOUR_OF_DAY) - myDate.get(Calendar.HOUR_OF_DAY);
    	if (hoursDiff < 0) {
        	// Invalid Time
        	// :@
        	return String.format("Today %s",
                	new SimpleDateFormat("hh:mm a").format(time));
    	} else if (hoursDiff > 3) {
        	// Not Same Hour, Hour Diff more than 3 hours
        	return String.format("Today %s",
                	new SimpleDateFormat("hh:mm a").format(time));
    	} else if (hoursDiff != 0) {
        	// Hours Diff less than 3 hours, but not
        	// current hour
        	int mintuesDiff = todayDate.get(Calendar.MINUTE) - myDate.get(Calendar.MINUTE);
        	return String.format("Before %d hour(s)",
                	hoursDiff) + (Math.abs(mintuesDiff) != 0
                	? String.format(" and %d minute(s)", Math.abs(mintuesDiff)) : "");
    	} else if (hoursDiff == 0) {
        	// Same Hours
        	int mintuesDiff = todayDate.get(Calendar.MINUTE) - myDate.get(Calendar.MINUTE);
        	if (mintuesDiff < 1) {
            	// Seconds Only {Same Minute}
            	int secondsDiff = todayDate.get(Calendar.SECOND) - myDate.get(Calendar.SECOND);
            	return String.format("Before %d second(s)", Math.abs(secondsDiff));
        	} else {
            	return String.format("Before %d minute(s)", Math.abs(mintuesDiff));
        	}
    	}
    	// Default
    	return DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(myDate);
	}

	public static void main(String[] args) {
    	long timeInLong = 1313529871880L;  // before 2 hours
    	System.out.println(formatDate(timeInLong));
	}
}

Software Developer
Mahmoudkelany.com


 

#23
Wajdy Essam كتب:

قمت بتحويل من دوال الDate الى الCalendar حيث أن الأولى أغلب دوالها Deprecated :

جميل يا وجدي

لقد تحسن الاداء :happy:

#24

أخي محمود هذه مجرد طريقة أخرى لحساب الفرق، يمكن طرح الفيم باستخدام الثوابت المختلفة في الCalendar ك :

Calendar.get(Calendar.HOUR_OF_DAY)

للحصول على نفس النتيجة.

بالتوفيق،

http://informatic-ar.com منصة تعليمية عربية في علوم الحاسب والبرمجة

https://moalfat.com  للكتب الالكترونية والكورسات التعليمية

Everything we see now is just an engineering solution based on old science

#25
.S.T.A.L.K.E.R كتب:

جميل يا وجدي

لقد تحسن الاداء :happy:

هل كود صغير مثل هذا يؤدي إلى بطئ في الأداء ؟

هل الجافا بطيئة لهذا الحد ؟

مواضيع مشابهة