display timestamped text in swift

To display timestamped text in Swift, you can use the DateFormatter class to format an instance of Date into a string representation with the desired timestamp format. Here's an example:

main.swift
import Foundation

func displayTimestampedText(text: String) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // Define the timestamp format
    
    let timestamp = dateFormatter.string(from: Date()) // Get the current timestamp
    
    let timestampedText = "\(timestamp): \(text)"
    print(timestampedText)
}

displayTimestampedText(text: "Hello, world!")
407 chars
14 lines

In this example, we define the timestamp format using the dateFormat property of the DateFormatter class. You can customize the format according to your needs.

The string(from:) method is used to convert the current Date object into a string representation using the defined timestamp format.

Finally, we concatenate the timestamped text with the original text and display the result using print(). The output will be something like:

main.swift
2021-10-18 12:34:56: Hello, world!
35 chars
2 lines

Note: Make sure to import the Foundation framework to gain access to the DateFormatter class.

Remember to replace "Hello, world!" with the actual text you want to display.

related categories

gistlibby LogSnag