Calculating Dates in Kotlin










0















The code below works well I am trying to figure how to calculate total number of days once the dates have been selected. Thank you so much.



The problem I'm trying to solve:
Select vacation start date - date selector - this part works well
Select vacation end date - date selector - this part works well
Total days =Calculate End date - Start date - I don't know how to conduct the calculations
Total 10 days



Here is my code



class VacationActivity : AppCompatActivity() 

private var selectedYear = 0
private var selectedMonth = 0
private var selectedDay = 0

@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_vacation)


// get view
val tvDate = findViewById<TextView>(R.id.from_date_view)
tvDate.setOnClickListener

val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)


if (tvDate.text.isNotEmpty())
this.selectedYear
this.selectedMonth
this.selectedDay


var listener = DatePickerDialog.OnDateSetListener view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay

tvDate.text = "$selectedMonth + 1/$selectedDay/$selectedYear"


val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()



val tvDate2 = findViewById<TextView>(R.id.to_date_view)
tvDate2.setOnClickListener

val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)


if (tvDate2.text.isNotEmpty())
this.selectedYear
this.selectedMonth
this.selectedDay


var listener = DatePickerDialog.OnDateSetListener view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay

tvDate2.text = "$selectedMonth + 1/$selectedDay/$selectedYear"


val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()
















share|improve this question
























  • what kind of problem you faced in the code?

    – sasikumar
    Nov 13 '18 at 11:54











  • Please describe, what is the issue in your code. Is it working or not, if not then which line failing.

    – Akshay Paliwal
    Nov 13 '18 at 12:03






  • 1





    so far the code works well. The date pickers are displaying the information but I don't know how to do the calculation. Thank you so much

    – Simona Buga
    Nov 13 '18 at 12:32











  • Possible duplicate of date difference in days, in Android (i know that that question doesn’t use Kotlin code, so you would have to translate).

    – Ole V.V.
    Nov 13 '18 at 13:12















0















The code below works well I am trying to figure how to calculate total number of days once the dates have been selected. Thank you so much.



The problem I'm trying to solve:
Select vacation start date - date selector - this part works well
Select vacation end date - date selector - this part works well
Total days =Calculate End date - Start date - I don't know how to conduct the calculations
Total 10 days



Here is my code



class VacationActivity : AppCompatActivity() 

private var selectedYear = 0
private var selectedMonth = 0
private var selectedDay = 0

@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_vacation)


// get view
val tvDate = findViewById<TextView>(R.id.from_date_view)
tvDate.setOnClickListener

val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)


if (tvDate.text.isNotEmpty())
this.selectedYear
this.selectedMonth
this.selectedDay


var listener = DatePickerDialog.OnDateSetListener view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay

tvDate.text = "$selectedMonth + 1/$selectedDay/$selectedYear"


val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()



val tvDate2 = findViewById<TextView>(R.id.to_date_view)
tvDate2.setOnClickListener

val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)


if (tvDate2.text.isNotEmpty())
this.selectedYear
this.selectedMonth
this.selectedDay


var listener = DatePickerDialog.OnDateSetListener view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay

tvDate2.text = "$selectedMonth + 1/$selectedDay/$selectedYear"


val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()
















share|improve this question
























  • what kind of problem you faced in the code?

    – sasikumar
    Nov 13 '18 at 11:54











  • Please describe, what is the issue in your code. Is it working or not, if not then which line failing.

    – Akshay Paliwal
    Nov 13 '18 at 12:03






  • 1





    so far the code works well. The date pickers are displaying the information but I don't know how to do the calculation. Thank you so much

    – Simona Buga
    Nov 13 '18 at 12:32











  • Possible duplicate of date difference in days, in Android (i know that that question doesn’t use Kotlin code, so you would have to translate).

    – Ole V.V.
    Nov 13 '18 at 13:12













0












0








0








The code below works well I am trying to figure how to calculate total number of days once the dates have been selected. Thank you so much.



The problem I'm trying to solve:
Select vacation start date - date selector - this part works well
Select vacation end date - date selector - this part works well
Total days =Calculate End date - Start date - I don't know how to conduct the calculations
Total 10 days



Here is my code



class VacationActivity : AppCompatActivity() 

private var selectedYear = 0
private var selectedMonth = 0
private var selectedDay = 0

@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_vacation)


// get view
val tvDate = findViewById<TextView>(R.id.from_date_view)
tvDate.setOnClickListener

val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)


if (tvDate.text.isNotEmpty())
this.selectedYear
this.selectedMonth
this.selectedDay


var listener = DatePickerDialog.OnDateSetListener view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay

tvDate.text = "$selectedMonth + 1/$selectedDay/$selectedYear"


val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()



val tvDate2 = findViewById<TextView>(R.id.to_date_view)
tvDate2.setOnClickListener

val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)


if (tvDate2.text.isNotEmpty())
this.selectedYear
this.selectedMonth
this.selectedDay


var listener = DatePickerDialog.OnDateSetListener view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay

tvDate2.text = "$selectedMonth + 1/$selectedDay/$selectedYear"


val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()
















share|improve this question
















The code below works well I am trying to figure how to calculate total number of days once the dates have been selected. Thank you so much.



The problem I'm trying to solve:
Select vacation start date - date selector - this part works well
Select vacation end date - date selector - this part works well
Total days =Calculate End date - Start date - I don't know how to conduct the calculations
Total 10 days



Here is my code



class VacationActivity : AppCompatActivity() 

private var selectedYear = 0
private var selectedMonth = 0
private var selectedDay = 0

@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_vacation)


// get view
val tvDate = findViewById<TextView>(R.id.from_date_view)
tvDate.setOnClickListener

val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)


if (tvDate.text.isNotEmpty())
this.selectedYear
this.selectedMonth
this.selectedDay


var listener = DatePickerDialog.OnDateSetListener view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay

tvDate.text = "$selectedMonth + 1/$selectedDay/$selectedYear"


val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()



val tvDate2 = findViewById<TextView>(R.id.to_date_view)
tvDate2.setOnClickListener

val currentDate = Calendar.getInstance()
val year = currentDate.get(Calendar.YEAR)
val month = currentDate.get(Calendar.MONTH)
val day = currentDate.get(Calendar.DAY_OF_MONTH)


if (tvDate2.text.isNotEmpty())
this.selectedYear
this.selectedMonth
this.selectedDay


var listener = DatePickerDialog.OnDateSetListener view, selectedYear, selectedMonth, selectedDay ->
this.selectedYear = selectedYear
this.selectedMonth = selectedMonth
this.selectedDay = selectedDay

tvDate2.text = "$selectedMonth + 1/$selectedDay/$selectedYear"


val datePicker = DatePickerDialog(this, listener, year, month, day)
datePicker.show()













date kotlin datepicker






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 12:38







Simona Buga

















asked Nov 13 '18 at 11:47









Simona BugaSimona Buga

167




167












  • what kind of problem you faced in the code?

    – sasikumar
    Nov 13 '18 at 11:54











  • Please describe, what is the issue in your code. Is it working or not, if not then which line failing.

    – Akshay Paliwal
    Nov 13 '18 at 12:03






  • 1





    so far the code works well. The date pickers are displaying the information but I don't know how to do the calculation. Thank you so much

    – Simona Buga
    Nov 13 '18 at 12:32











  • Possible duplicate of date difference in days, in Android (i know that that question doesn’t use Kotlin code, so you would have to translate).

    – Ole V.V.
    Nov 13 '18 at 13:12

















  • what kind of problem you faced in the code?

    – sasikumar
    Nov 13 '18 at 11:54











  • Please describe, what is the issue in your code. Is it working or not, if not then which line failing.

    – Akshay Paliwal
    Nov 13 '18 at 12:03






  • 1





    so far the code works well. The date pickers are displaying the information but I don't know how to do the calculation. Thank you so much

    – Simona Buga
    Nov 13 '18 at 12:32











  • Possible duplicate of date difference in days, in Android (i know that that question doesn’t use Kotlin code, so you would have to translate).

    – Ole V.V.
    Nov 13 '18 at 13:12
















what kind of problem you faced in the code?

– sasikumar
Nov 13 '18 at 11:54





what kind of problem you faced in the code?

– sasikumar
Nov 13 '18 at 11:54













Please describe, what is the issue in your code. Is it working or not, if not then which line failing.

– Akshay Paliwal
Nov 13 '18 at 12:03





Please describe, what is the issue in your code. Is it working or not, if not then which line failing.

– Akshay Paliwal
Nov 13 '18 at 12:03




1




1





so far the code works well. The date pickers are displaying the information but I don't know how to do the calculation. Thank you so much

– Simona Buga
Nov 13 '18 at 12:32





so far the code works well. The date pickers are displaying the information but I don't know how to do the calculation. Thank you so much

– Simona Buga
Nov 13 '18 at 12:32













Possible duplicate of date difference in days, in Android (i know that that question doesn’t use Kotlin code, so you would have to translate).

– Ole V.V.
Nov 13 '18 at 13:12





Possible duplicate of date difference in days, in Android (i know that that question doesn’t use Kotlin code, so you would have to translate).

– Ole V.V.
Nov 13 '18 at 13:12












1 Answer
1






active

oldest

votes


















1














You can use these functions:



fun getLocalDateFromString(d: String, format: String): LocalDate 
return LocalDate.parse(d, DateTimeFormatter.ofPattern(format))



it returns a LocalDate from a string d formatted with format.



fun getDaysDif(fromDate: LocalDate, toDate: LocalDate): Long 
return ChronoUnit.DAYS.between(fromDate, toDate)



it returns the difference in days between 2 dates (LocalDate)



So you can do:



val days = getDaysDif(
getLocalDateFromString(tvDate1.text, "MM/dd/yyyy"),
getLocalDateFromString(tvDate2.text, "MM/dd/yyyy"))


The above code works for API level 26 and above.



For lower versions, use this:



val format = SimpleDateFormat("MM/dd/yyyy")
val days = TimeUnit.DAYS.convert(
format.parse(tvDate2.text).getTime() -
format.parse(tvDate1.text).getTime(),
TimeUnit.MILLISECONDS)





share|improve this answer
























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53280392%2fcalculating-dates-in-kotlin%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You can use these functions:



    fun getLocalDateFromString(d: String, format: String): LocalDate 
    return LocalDate.parse(d, DateTimeFormatter.ofPattern(format))



    it returns a LocalDate from a string d formatted with format.



    fun getDaysDif(fromDate: LocalDate, toDate: LocalDate): Long 
    return ChronoUnit.DAYS.between(fromDate, toDate)



    it returns the difference in days between 2 dates (LocalDate)



    So you can do:



    val days = getDaysDif(
    getLocalDateFromString(tvDate1.text, "MM/dd/yyyy"),
    getLocalDateFromString(tvDate2.text, "MM/dd/yyyy"))


    The above code works for API level 26 and above.



    For lower versions, use this:



    val format = SimpleDateFormat("MM/dd/yyyy")
    val days = TimeUnit.DAYS.convert(
    format.parse(tvDate2.text).getTime() -
    format.parse(tvDate1.text).getTime(),
    TimeUnit.MILLISECONDS)





    share|improve this answer





























      1














      You can use these functions:



      fun getLocalDateFromString(d: String, format: String): LocalDate 
      return LocalDate.parse(d, DateTimeFormatter.ofPattern(format))



      it returns a LocalDate from a string d formatted with format.



      fun getDaysDif(fromDate: LocalDate, toDate: LocalDate): Long 
      return ChronoUnit.DAYS.between(fromDate, toDate)



      it returns the difference in days between 2 dates (LocalDate)



      So you can do:



      val days = getDaysDif(
      getLocalDateFromString(tvDate1.text, "MM/dd/yyyy"),
      getLocalDateFromString(tvDate2.text, "MM/dd/yyyy"))


      The above code works for API level 26 and above.



      For lower versions, use this:



      val format = SimpleDateFormat("MM/dd/yyyy")
      val days = TimeUnit.DAYS.convert(
      format.parse(tvDate2.text).getTime() -
      format.parse(tvDate1.text).getTime(),
      TimeUnit.MILLISECONDS)





      share|improve this answer



























        1












        1








        1







        You can use these functions:



        fun getLocalDateFromString(d: String, format: String): LocalDate 
        return LocalDate.parse(d, DateTimeFormatter.ofPattern(format))



        it returns a LocalDate from a string d formatted with format.



        fun getDaysDif(fromDate: LocalDate, toDate: LocalDate): Long 
        return ChronoUnit.DAYS.between(fromDate, toDate)



        it returns the difference in days between 2 dates (LocalDate)



        So you can do:



        val days = getDaysDif(
        getLocalDateFromString(tvDate1.text, "MM/dd/yyyy"),
        getLocalDateFromString(tvDate2.text, "MM/dd/yyyy"))


        The above code works for API level 26 and above.



        For lower versions, use this:



        val format = SimpleDateFormat("MM/dd/yyyy")
        val days = TimeUnit.DAYS.convert(
        format.parse(tvDate2.text).getTime() -
        format.parse(tvDate1.text).getTime(),
        TimeUnit.MILLISECONDS)





        share|improve this answer















        You can use these functions:



        fun getLocalDateFromString(d: String, format: String): LocalDate 
        return LocalDate.parse(d, DateTimeFormatter.ofPattern(format))



        it returns a LocalDate from a string d formatted with format.



        fun getDaysDif(fromDate: LocalDate, toDate: LocalDate): Long 
        return ChronoUnit.DAYS.between(fromDate, toDate)



        it returns the difference in days between 2 dates (LocalDate)



        So you can do:



        val days = getDaysDif(
        getLocalDateFromString(tvDate1.text, "MM/dd/yyyy"),
        getLocalDateFromString(tvDate2.text, "MM/dd/yyyy"))


        The above code works for API level 26 and above.



        For lower versions, use this:



        val format = SimpleDateFormat("MM/dd/yyyy")
        val days = TimeUnit.DAYS.convert(
        format.parse(tvDate2.text).getTime() -
        format.parse(tvDate1.text).getTime(),
        TimeUnit.MILLISECONDS)






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 13 '18 at 13:14

























        answered Nov 13 '18 at 12:54









        forpasforpas

        12.7k3424




        12.7k3424





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53280392%2fcalculating-dates-in-kotlin%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Use pre created SQLite database for Android project in kotlin

            Darth Vader #20

            Ondo